Home > Software engineering >  Plotting graph and adding twinx() with seaborn
Plotting graph and adding twinx() with seaborn

Time:10-24

I am plotting a graph using seaborn, the code is:

fig, ax = plt.subplots(figsize=(20, 10))
ax2 = ax.twinx()

sns.barplot(x="dt_mvtc", y="qtde_t0",
         data=df_grafico_merge.query('t0_def_qtt==1'),color='blue',ax=ax)

sns.lineplot(x="dt_mvtc",y='qtde_t12', hue='t12_def_qtt', style='t12_def_qtt',
         data=df_grafico_merge.query('t0_def_qtt==1'),markers= True, color='orange', ax=ax2)

plt.xlabel("Data")
plt.ylabel("Quantidade")
plt.title('Qtde de registros por data e t0=1')
plt.xticks(rotation=90)

for axis in [ax.yaxis]:
    formatter = ScalarFormatter()
    formatter.set_scientific(True)
    axis.set_major_formatter(formatter)

plt.show()

And the output is:

Output

why the x axis are like that? Since I am using x=dt_mvtc in both, why are they mixing? Just for comparison, when I comment the line ax2 = ax.twinx(), the axis outputs right (that is, with dates rotated 90 and readable), so my problem is using the twinx(), but I do not where it is wrong. Any help?

CodePudding user response:

plt.xticks only uses the last subplot axis that is called. To get the rotated xticks add:

for ax_ in fig.axes:
    plt.sca(ax_)
    plt.xticks(rotation=90)
    
  • Related