Danjiri
Danjiri

Reputation: 37

Creating a single barplot with different colors with pandas and matplotlib

I have two dfs, for which I want to create a single bar plot, each bar needs its own color depending on which df it came from.

# Ages < 20
df1.tags = ['locari', 'ママコーデ', 'ponte_fashion', 'kurashiru', 'fashion']
df1.tag_count = [2162, 1647, 1443, 1173, 1032]

# Ages 20 - 24
df2.tags= ['instagood', 'ootd', 'fashion', 'followme', 'love']
df2.tag_count = [6523, 4576, 3986, 3847, 3599]

How do I create such a plot?

P.S. The original df is way bigger. Some words may overlap, but I want them to have different colors as well

Upvotes: 0

Views: 233

Answers (1)

alexblae
alexblae

Reputation: 746

Your data frame tag_counts are just simple lists, so you can use standard mpl bar plots to plot both of them in the same axis. This answer assumes that both dataframes have the same length.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Create dataframes
df1=pd.DataFrame()
df2=pd.DataFrame()

# Ages < 20
df1.tags = ['locari', 'blub', 'ponte_fashion', 'kurashiru', 'fashion']
df1.tag_count = [2162, 1647, 1443, 1173, 1032]

# Ages 20 - 24
df2.tags= ['instagood', 'ootd', 'fashion', 'followme', 'love']
df2.tag_count = [6523, 4576, 3986, 3847, 3599]

# Create figure
fig=plt.figure()
ax=fig.add_subplot(111)

# x-coordinates
ind1 = np.arange(len(df1.tag_count))
ind2 = np.arange(len(df2.tag_count))
width = 0.35

# Bar plot for df1
ax.bar(ind1,df1.tag_count,width,color='r')

# Bar plot for df1
ax.bar(ind2+width,df2.tag_count,width,color='b')

# Create new xticks
ticks=list(ind1+0.5*width)+list(ind2+1.5*width)
ticks.sort()
ax.set_xticks(ticks)

# Sort labels in an alternating way
labels = [None]*(len(df1.tags)+len(df2.tags))
labels[::2] = df1.tags
labels[1::2] = df2.tags
ax.set_xticklabels(labels)

plt.show()

This will return a plot like this

enter image description here

Note that to merge both tags into a single list I assumed that both lists have the same length.

Upvotes: 2

Related Questions