a1234
a1234

Reputation: 821

matplotlib double bar graph with pandas series

I have the following:

indyes = tuple(yesSeries.index)
indno = tuple(nodSeries.index)
width = 3

p1 = plt.bar(indyes, yesSeries, label="Example one", color='SkyBlue')
p2 = plt.bar(indno, nodSeries, label="Example two", color='IndianRed')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')

plt.title('Epic Graph\nAnother Line! Whoa')

plt.show()

It plots my graph as a stacked bar graph: enter image description here

When I try to add + width to the second bar graph, indno + width so they are not stacked, rather side by side I get the following error: TypeError: can only concatenate tuple (not "int") to tuple.

I have set my Pandas Series into a tuple to extract the date and count information.

How can I get two parallel vertical bar plots?

Upvotes: 7

Views: 11530

Answers (1)

Cedric Zoppolo
Cedric Zoppolo

Reputation: 4743

I believe that what you are looking for can be done creating a DataFrame from your Series and then using the plot.bar function.

In below code I generate data and create the graph as you may want to.

import matplotlib.pyplot as plt
import pandas as pd
times = pd.date_range('2018-09-01', periods=7, freq='5D')
yesSeries = pd.Series([1800,2000,3000,1000,2000,1500,1700], index=times)
nodSeries = pd.Series([200,500,700,600,300,50,0], index=times)

df = pd.DataFrame({"Example one":yesSeries,"Example two":nodSeries})
ax = df.plot.bar(color=["SkyBlue","IndianRed"], rot=0, title="Epic Graph\nAnother Line! Whoa")
ax.set_xlabel("date")
ax.set_ylabel("counts")
ax.xaxis.set_major_formatter(plt.FixedFormatter(times.strftime("%b %d %Y")))
plt.show()

This results in below graph.

Bar plot

If it seems that the dates appear to be cluttered you can insert below line before the plt.show() code:

plt.gcf().autofmt_xdate()

Which would result in below graph.

Bar plot with dates with autofmt

Upvotes: 18

Related Questions