<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/plotting-data-online-via-plotly-and-python/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/plotting-data-online-via-plotly-and-python/"> DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I don’t do a lot of plotting in my job, but I recently heard about a website called <a target="_blank" rel="nofollow" href="https://plot.ly/">Plotly</a> that provides a plotting service for anyone’s data. They even have a plotly package for Python (among others)! So in this article we will be learning how to plot with their package. Let’s have some fun making graphs!</p>
<h2>Getting Started</h2>
<p>You will need the plotly package to follow along with this article. You can use pip to get the package and install it:</p>
<pre>pip install plotly</pre>
<p>Now that you have it installed, you’ll need to go to the Plotly website and create a free account. Once that’s done, you will get an API key. To make things super simple, you can use your username and API key to create a credentials file. Here’s how to do that:</p>
<pre>
import plotly.tools as tls

tls.set_credentials_file(
        username=&quot;your_username&quot;, 
        api_key=&quot;your_api_key&quot;)

# to get your credentials
credentials = tls.get_credentials_file()
</pre>
<p>If you don’t want to save your credentials, then you can also sign in to their service by doing the following:</p>
<pre>
import plotly.plotly as py
py.sign_in('your_username','your_api_key')
</pre>
<p>For the purposes of this article, I’m assuming you have created the credentials file. I found that makes interacting with their service a bit easier to use.</p>
<h2>Creating a Graph</h2>
<p>Plotly seems to default to a Scatter Plot, so we’ll start with that. I decided to grab some data from a <a target="_blank" rel="nofollow" href="http://census.ire.org/data/bulkdata.html">census website</a>. You can download any US state’s population data, along with other pieces of data. In this case, I downloaded a CSV file that contained the population of each county in the state of Iowa. Let’s take a look:</p>
<pre>
import csv
import plotly.plotly as py

#----------------------------------------------------------------------
def plot_counties(csv_path):
    &quot;&quot;&quot;
    http://census.ire.org/data/bulkdata.html
    &quot;&quot;&quot;
    counties = {}
    county = []
    pop = []
    
    counter = 0
    with open(csv_path) as csv_handler:
        reader = csv.reader(csv_handler)
        for row in reader:
            if counter  == 0:
                counter += 1
                continue
            county.append(row[8])
            pop.append(row[9])
            
    trace = dict(x=county, y=pop)
    data = [trace]
    py.plot(data, filename='ia_county_populations')
    
if __name__ == '__main__':
    csv_path = 'ia_county_pop.csv'
    plot_counties(csv_path)
</pre>
<p>If you run this code, you should see a graph that looks like this:<br>
<a title="" data-rel="lightbox-0" target="_blank" rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/04/ploty-python.png?ssl=1"><img sizes="(max-width: 490px) 100vw, 490px" alt="" class="wp-image-6310" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/04/ploty-python-490x327.png?w=450&ssl=1" data-recalc-dims="1"></a></p>
<p>You can also view the graph <a target="_blank" rel="nofollow" href="https://plot.ly/~driscollis/0">here</a>. Anyway, as you can see in the code above, all I did was read the CSV file and extract out the county name and the population. Then I put that data into two different Python lists. Finally I created a dictionary of those lists and then wrapped that dictionary in a list. So you end up with a list that contains a dictionary that contains two lists! To make the Scatter Plot, I passed the data to plotly’s <strong>plot</strong> method.</p>
<h2>Converting to a Bar Chart</h2>
<p>Now let’s see if we can change the ScatterPlot to a Bar Chart. First off, we’ll play around with the plot data. The following was done via the Python interpreter:</p>
<pre>
>>> scatter = py.get_figure('driscollis', '0')
>>> print scatter.to_string()
Figure(
    data=Data([
        Scatter(
            x=[u'Adair County', u'Adams County', u'Allamakee County', u'..', ],
            y=[u'7682', u'4029', u'14330', u'12887', u'6119', u'26076', '..'  ]
        )
    ])
)
</pre>
<p>This shows how we can grab the figure using the username and the plot’s unique number. Then we printed out the data structure. You will note that it doesn’t print out the entire data structure. Now let’s do the actual conversion to a Bar Chart:</p>
<pre>
from plotly.graph_objs import Data, Figure, Layout

scatter_data = scatter.get_data()
trace_bar = Bar(scatter_data[0])
data = Data([trace_bar])
layout = Layout(title=&quot;IA County Populations&quot;)
fig = Figure(data=data, layout=layout)
py.plot(fig, filename='bar_ia_county_pop')
</pre>
<p>This will create a bar chart at the following URL: <a target="_blank" rel="nofollow" href="https://plot.ly/~driscollis/1">https://plot.ly/~driscollis/1</a>. </p>
<p>Here’s the image of the graph:<br>
<a title="" data-rel="lightbox-1" target="_blank" rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/04/ploty-python2.png?ssl=1"><img sizes="(max-width: 490px) 100vw, 490px" alt="" class="wp-image-6311" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/04/ploty-python2-490x359.png?w=450&ssl=1" data-recalc-dims="1"></a></p>
<p>This code is slightly different than the code we used originally. In this case, we explicitly created a <strong>Bar</strong> object and passed it the scatter plot’s data. Then we put that data into a <strong>Data</strong> object. Next we created a <strong>Layout</strong> object and gave our chart a title. Then we created a <strong>Figure</strong> object using the data and layout objects. Finally we plotted the bar chart. </p>
<h2>Saving the Graph to Disk</h2>
<p>Plotly also allows you to save your graph to your hard drive. You can save it in the following formats: png, svg, jpeg, and pdf. Assuming you still have the Figure object from the previous example handy, you can do the following:</p>
<pre>
py.image.save_as(fig, filename='graph.png')
</pre>
<p>If you want to save using one of the other formats, then just use that format’s extension in the filename.</p>
<h2>Wrapping Up</h2>
<p>At this point you should be able to use the plotly package pretty well. There are many other graph types available, so be sure to read Plotly’s documentation thoroughly. They also support streaming graphs. As I understand it, Plotly allows you to create 10 graphs for free. After that you would either have to delete some of your graphs or pay a monthly fee. </p>
<p><strong>Additional Reading</strong></p>
<ul>
<li>Plotly Python <a target="_blank" rel="nofollow" href="https://plot.ly/python/">documentation</a></li>
<li>Plotly <a target="_blank" rel="nofollow" href="https://plot.ly/python/user-guide/">User Guide</a></li>
</ul>
<p>If you have question you can leave a comment below.</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a title="Permanent Link toUsing PostgreSQL and shiny with a dynamic leaflet map: monitoring trash cans" target="_blank" rel="nofollow" href="https://datascienceplus.com/using-postgresql-and-shiny-with-a-dynamic-leaflet-map-monitoring-trash-cans/">Using PostgreSQL and shiny with a dynamic leaflet map: monitoring trash cans</a></li>
<li><a title="Permanent Link toVisualizing Streaming Data And Alert Notification with Shiny" target="_blank" rel="nofollow" href="https://datascienceplus.com/visualizing-streaming-data-with-shiny/">Visualizing Streaming Data And Alert Notification with Shiny</a></li>
<li><a title="Permanent Link toMetro Systems Over Time: Part 3" target="_blank" rel="nofollow" href="https://datascienceplus.com/metro-systems-over-time-part-3/">Metro Systems Over Time: Part 3</a></li>
<li><a title="Permanent Link toMetro Systems Over Time: Part 2" target="_blank" rel="nofollow" href="https://datascienceplus.com/metro-systems-over-time-part-2/">Metro Systems Over Time: Part 2</a></li>
<li><a title="Permanent Link toMetro Systems Over Time: Part 1" target="_blank" rel="nofollow" href="https://datascienceplus.com/metro-systems-over-time-part-1/">Metro Systems Over Time: Part 1</a></li>
</ol></strong>
<div>
<a target="_blank" rel="nofollow" href="http://feeds.feedburner.com/~ff/datascienceplus?a=rTnAsJyWW7U:prbgMIns-G4:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/datascienceplus?i=rTnAsJyWW7U:prbgMIns-G4:D7DqB2pKExk" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.feedburner.com/~ff/datascienceplus?a=rTnAsJyWW7U:prbgMIns-G4:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=qj6IDK7rITs" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.feedburner.com/~ff/datascienceplus?a=rTnAsJyWW7U:prbgMIns-G4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=yIl2AUoC8zA" border="0"></a>
</div>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datascienceplus.com/plotting-data-online-via-plotly-and-python/"> DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/nMVwGj2THD0"></a></div>