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