【问题标题】:pandas plot with twiny top xticks anchor adjustmentpandas plot with twiny top xticks 锚调整
【发布时间】:2021-04-03 01:54:26
【问题描述】:

我有两个长长的 xticks,带有扭曲的情节。底部标签看起来不错!两个问题:

  1. 标签看起来像是被剪掉了。
  2. 顶部标签远侧指向刻度,如何调整近侧指向刻度? (使用不同的旋转?)

#!/usr/bin/env python3
import matplotlib.pyplot as plt
import pandas as pd

fig = plt.figure()
ax = fig.add_subplot(111)
df1 = pd.DataFrame()
idx = 0
for i in range(1,50):
    df1.loc[idx,'name'] = 'AAAAAAAAAA' + str(i)
    df1.loc[idx,'value'] = 40*i
    idx += 1
    
df2 = pd.DataFrame()
idx = 0
for i in range(1,50):
    df2.loc[idx,'name'] = 'BBBBBBBBBB' + str(i)
    df2.loc[idx,'value'] = i*i
    idx += 1
ax2 = ax.twiny()
df1.plot(x='name',y='value',ax=ax)
df2.plot(x='name',y='value',ax=ax2)

fig.autofmt_xdate(rotation=45)
#plt.savefig(pngname)
plt.show()

【问题讨论】:

  • @BigBen 谢谢,已更新

标签: python matplotlib


【解决方案1】:

对标签的水平对齐方式和savefig 调用进行了一些调整,以便标签在保存时不会被截断。另外,请确保删除 fig.autofmt_xdate(rotation=45)

ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')
ax2.set_xticklabels(ax2.get_xticklabels(), rotation=45, ha='left')

plt.savefig(pngname, bbox_inches='tight')

输出:

【讨论】:

  • 很好的答案,autofmt_xdate 不起作用的原因是什么?
  • autofmt_xdate 使用右水平对齐 - ha='right' - 默认情况下。在这里,我认为您希望在ax 上右对齐,在ax2 上左对齐。所以你必须分别设置每个对齐方式。
猜你喜欢
  • 1970-01-01
  • 2015-04-03
  • 2014-12-09
  • 2019-05-01
  • 1970-01-01
  • 2022-12-28
  • 2023-01-09
  • 2014-06-21
  • 1970-01-01
相关资源
最近更新 更多