Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

307
Views
Why does merging two bar chart subplots into one change the axis and how can I fix this?

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:

subplots

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: After_joining

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 stacked bars for two dataframes with combined indices

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!