-1

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?

Dimitri
  • 109
  • 1
  • 14
  • 3
    Writing `ax2 = ax.twinx()` makes `ax2` the "current ax", upon which `plt.xticks()` is acting. You could try to follow `ax2 = ax.twinx()` with `plt.sca(ax)` to set `ax` again as "current ax". Alternatively, you could rotate the ticks via `for tick in ax.get_xticklabels(): tick.set_rotation(90)` – JohanC Oct 21 '21 at 20:25

1 Answers1

1

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)
    
BenT
  • 3,172
  • 3
  • 18
  • 38