I have two dataframes:
df1=pd.DataFrame(10*np.random.rand(4,3),index=[2,3,4,5],columns=["I","J","K"])
df2=pd.DataFrame(10*np.random.rand(4,3),index=[1,2,3,4],columns=["I","J","K"])
After creating a bar chart I get:
Now I want to merge them into one figure so I tried:
fig, ax = plt.subplots(sharex=True)
ax1 = df1.plot.bar(legend=True, rot=0, stacked=True, width=0.1, position=1, colormap="bwr", ax=ax, alpha=0.7)
ax2 = df2.plot.bar(legend=True, rot=0, stacked=True, width=0.1, position=0, colormap="BrBG", ax=ax, alpha=0.7)
plt.show()
But the result isn't what I would expect:

As you can see, I would want the x-axis to have values 1, 2, 3, 4, 5 and the graphs to correspond to their original index value. Where is the problem and how could I fix it?
Also if it was possible I would need to set the new axis values automatically since I have many of these dataframes all with different axis values and inserting the new axis values manually would take a long time. Maybe I could use .unique() in the index column and implement this somehow?
CodePudding user response:
You can reindex both dataframes to the same index:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df1 = pd.DataFrame(10 * np.random.rand(4, 3), index=[2, 3, 4, 5], columns=["I", "J", "K"])
df2 = pd.DataFrame(10 * np.random.rand(4, 3), index=[1, 2, 3, 4], columns=["I", "J", "K"])
fig, ax = plt.subplots()
combined_index = df1.index.union(df2.index)
df1.reindex(combined_index).plot.bar(legend=True, rot=0, stacked=True, width=0.1, position=1,
colormap="bwr", alpha=0.7, ax=ax)
df2.reindex(combined_index).plot.bar(legend=True, rot=0, stacked=True, width=0.1, position=0,
colormap="BrBG", alpha=0.7, ax=ax)
plt.show()
Pandas bar plot creates categorical x-ticks (internally numbered 0,1,2,...) using the dataframe's index. First the internal tick positions are assigned, and then the labels. By using the same index for both dataframes, the positions will coincide.


