DEV Community

threadspeed
threadspeed

Posted on

Plots with Plotly

Python programmers often use matplotlib to create plots, you can make all kinds of charts with it like bar charts or line charts. But this is not the only way to visualize your data.

A popular alternative the plotly module. This service lets you create plots and put them online. You should learn Python before trying plotly.

Create a bar plot

Creating a bar plot is done with a few lines of code.
To get started install plotly and chart-studio

pip install plotly==4.8.1 --user           
pip install chart-studio==1.0.0 --user

A simple bar plot can be created like this:

import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.show()

So the data in this case is a list with integers, but the list can contains different data types.

That opens up a server on localhost showing the bar plot. You can also save them to a file or host them online.

plotly plot

To share them online, import chart_studio and set your api keys.

import chart_studio
chart_studio.tools.set_credentials_file(username='DemoAccount', api_key='lr1c37zw81')

That gives you this code:

import plotly.graph_objects as go
import chart_studio
import chart_studio.plotly as py

chart_studio.tools.set_credentials_file(username='DemoAccount', api_key='lr1c37zw81')

data = [go.Bar(y=[1,2,3,4,5,6])]
py.plot(data, filename='bar-plot')

After setting up, you will get a bar chart like this.

Line chart

If you want a line chart, you can change it. It's very important to change the filename, or it will overwrite your previous chart.

g1 = go.Scatter(x=[1, 2, 3, 4], y=[2, 4, 6, 8])
g2 = go.Scatter(x=[1, 2, 3, 4], y=[5, 10, 15, 20])

data = [g1,g2]
py.plot(data, filename='line-plot')

That results in this line chart demo

plotly line chart

Top comments (0)