Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

305
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda