Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

303
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda