Plotly Front to Back: Bar Charts & Line Charts | by Dario Radečić | Towards Data Science

A couple of days ago I’ve announced an upcoming series dealing with the Plotly library, covering everything you need to know to take your visualizations to the next level. Although I recommend you to read the series from the beginning, articles are formed in that way that each one is independent and doesn’t require you to read everything before it.
Today you’ll read the second article in the series, where the first was dealing with only the reasons why should you even consider Plotly:
towardsdatascience.com
So make sure to check that one out if you’re struggling to choose a data visualization platform or just want to try something new.
Today, we’ll focus on two very common types of charts:
Bar charts
Line charts
The first one you’ll use almost anytime you want to see the difference between categories and the ladder is basically present in any dashboard out there, usually representing time-series data of some sort.
Without much ado, let’s jump in.
Imports-wise we’ll only have a few libraries, two of which are present in every data science notebook, and the last two are from Plotly:
import numpy as npimport pandas as pdimport plotly.graph_objs as go import plotly.offline as pyo
As for the dataset, we’ll declare something random in Pandas, let’s say various bill amounts for different months in a year:
df = pd.DataFrame(data={   ‘Month’: [‘January’, ‘February’, ‘March’],   ‘Water’: [50, 61, 43],   ‘Electricity’: [100, 88, 112],   ‘Heat’: [86, 92, 104],   ‘Total’: [236, 241, 259]})
Okay, we have everything to get started. Let’s explore all the different ways this dataset can be plotted.
We’ll cover three types of bar charts today:
(Normal) bar chartsNested bar chartsStacked bar charts
(Normal) bar charts
Nested bar charts
Stacked bar charts
You don’t need to know beforehand the differences between those as everything will be explained in the article. The idea is to show you every way you can represent data with bars, and then it’s up to you to choose the most suitable option.
Okay, let’s plot the Month on the x-axis and Total on the y-axis. As always, you’ll declare a figure object and put data and layout inside. This one is pretty simple and doesn’t need further explanation:
fig = go.Figure(   data=[       go.Bar(           x=df[‘Month’],           y=df[‘Total’]       )   ],   layout=go.Layout(       title=’Total Monthly Cost’   ))pyo.plot(fig)
If you were to execute this code, a plot like this would come out:
Okay, not bad, but not great either — here we’re only displaying the total amounts, which isn’t showing us the whole picture. Let’s see how to improve.
In this one, we’ll be able to visualize each expense and not only the total amounts. Keep in mind, if you have a lot of data and a lot of categories this type of chart might become hard to look at — but it is just fine for our case.
And it’s really simple to do so — we only need to put a go.Bar object in our data array for every category we want to visualize. Here’s the code:
fig = go.Figure(   data=[       go.Bar(           x=df[‘Month’],           y=df[‘Water’],           name=’Water’,           marker=dict(color=’#3498db’)       ),       go.Bar(           x=df[‘Month’],           y=df[‘Electricity’],           name=’Electricity’,           marker=dict(color=’#f1c40f’)       ),       go.Bar(           x=df[‘Month’],           y=df[‘Heat’],           name=’Heat’,           marker=dict(color=’#e74c3c’)       )   ],   layout=go.Layout(       title=’Monthly Cost per Item’   ))pyo.plot(fig)
Executing the above code would produce a nice-looking chart:
If you ask me, this is a great improvement from what we’ve had previously. Let’s explore another option before concluding this section.
In most cases this is my favorite option. Takes as little space as your regular bar chart, and displays as much information as a nested bar chart. The code is pretty much identical as the one for a nested bar chart, the only difference is that you need to specify barmode='stack' in the layout.
Let’s see this in action:
fig = go.Figure(   data=[       go.Bar(           x=df[‘Month’],           y=df[‘Water’],           name=’Water’,           marker=dict(color=’#3498db’)       ),       go.Bar(           x=df[‘Month’],           y=df[‘Electricity’],           name=’Electricity’,           marker=dict(color=’#f1c40f’)       ),       go.Bar(           x=df[‘Month’],           y=df[‘Heat’],           name=’Heat’,           marker=dict(color=’#e74c3c’)       )   ],   layout=go.Layout(       title=’Monthly Cost per Item’,       barmode=’stack’   ))pyo.plot(fig)
Executing the above code would result in a chart like this one:
Great! We’ve covered bar charts in-depth, let’s now see what can we do with line charts!
For this part, we’ll only need two Numpy arrays:
x = np.linspace(0, 49, 50)y = np.random.randint(10, 20, 50)
And that’s it — we can begin exploring.
As with the bar charts, we’ll cover two options:
Basic Line Chart
Line Chart with Markers
Multiple Line Chart
If it’s not clear to you what is meant with the second option, bear with me for a minute.
Here’s how we can make a basic line chart from those two previously declared Numpy arrays:
fig = go.Figure(   data=[       go.Scatter(          x=x,          y=y,          mode=’lines’        )   ],   layout=go.Layout(       title=’Line Chart’   ))pyo.plot(fig)
Executing this code will result in the following chart:
Not the best-looking line chart, we’ll explore how to tweak the visuals towards the end of the article.
If you don’t have too many data points, sometimes is convenient to show little markers alongside the lines. Code-wise changes are minimal — as we only need to tweak the mode option, and set it as mode='lines+markers'. Let’s see the code:
fig = go.Figure(   data=[       go.Scatter(           x=x,           y=y,           mode=’lines+markers’        )   ],   layout=go.Layout(       title=’Line Chart’   ))pyo.plot(fig)
Executing the above-written code will result in this chart:
Nice. Let’s now see how we can combine multiple lines into a single line chart.
Let’s now see how easy it is to combine multiple lines into a single chart. Just like with the bar chart, we’ll put multiple go.Scatter objects into our data array.
To spicy things up a bit, we added a few layout options just to give you a feel of what can be done, appearance-wise.
Here’s the code:
fig = go.Figure(   data=[     go.Scatter(         x=x,         y=y,         mode=’lines’,         name=’Lines’,         line=dict(             color=’#3498db’,             width=4         )     ),     go.Scatter(         x=x,         y=y + 10,         mode=’lines+markers’,         name=’Lines + Markers’,         line=dict(             color=’#f1c40f’,             dash=’dash’,             width=4         )       )   ],   layout=go.Layout(       title=’Line Chart’,       hovermode=’x’   ))pyo.plot(fig)
Executing the code will produce this chart:
Awesome! And that will be just enough for today.
This was quite a longer article than I usually write. But I hope you’ve managed to follow along. We covered a lot of ground today, but there’s still much more to come.
The following article will cover scatter charts and bubble charts, so stay tuned if that’s something that you’d find interesting.
Thanks for reading, and as always don’t hesitate to put your questions and comments below.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.