简体   繁体   English

使用辅助 y 轴时共享 x 轴

[英]Share x-axis when using secondary y-axis

When creating a chart with a secondary y-axis, which is based on a pandas dataframe, I am struggling to share the x-axis.创建带有辅助 y 轴的图表时,该图表基于 Pandas 数据框,我正在努力共享 x 轴。 I am mostly lending from the solution here , where I like the EDIT of the accepted answer.我主要是从这里的解决方案中借出,我喜欢接受答案的编辑。

When recreating this solution using my own toy dataframe, I am facing the issue that my x-axis doesn't look too good.使用我自己的玩具数据框重新创建此解决方案时,我面临的问题是我的 x 轴看起来不太好。

df = pd.DataFrame(np.random.randint(0, 100, (20, 2)),
                  index=pd.date_range('20190101', periods=20),
                  columns=list('AB'))

fig, ax = plt.subplots()

ax.plot(df.index, df['A'], 'blue', label='Line A')

ax2 = ax.twinx()
ax2.plot(df.index, df['B'], 'red', label='Line B')

lines = ax.get_lines() + ax2.get_lines()

ax.legend(lines, [l.get_label() for l in lines],
          loc='upper left', frameon=False, fontsize=20)

在此处输入图片说明

One way to solve this is to rotate the x-tick labels:解决此问题的一种方法是旋转 x-tick 标签:

df = pd.DataFrame(np.random.randint(0, 100, (20, 2)),
                  index=pd.date_range('20190101', periods=20),
                  columns=list('AB'))

fig, ax = plt.subplots()
plt.xticks(rotation=70)

ax.plot(df.index, df['A'], 'blue', label='Line A')

ax2 = ax.twinx()
ax2.plot(df.index, df['B'], 'red', label='Line B')

lines = ax.get_lines() + ax2.get_lines()



ax.legend(lines, [l.get_label() for l in lines],
          loc='upper left', frameon=False, fontsize=20)

Output:输出:

在此处输入图片说明

Another option is just to increase the figure size or decrease the label font-size so that the labels no longer overlap.另一种选择是增加图形大小或减小标签字体大小,以便标签不再重叠。

fig, ax = plt.subplots(figsize=(15,10))

Output:输出:

在此处输入图片说明

You can use pandas' builtin command, which provides some interesting tick labels:您可以使用 pandas 的内置命令,它提供了一些有趣的刻度标签:

fig, ax = plt.subplots()
df.plot(y=['A','B'], secondary_y='B', ax=ax)

Output:输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM