【问题标题】:My graph doesn't display entirely x-axis and grid in the background (Matplotlib/Python)我的图表在背景中没有完全显示 x 轴和网格(Matplotlib/Python)
【发布时间】:2019-12-23 14:23:55
【问题描述】:

我正在尝试在带有辅助 Y 轴的图表上针对 EBIT 绘制一些 revenues。 一切似乎都很好,除了

  • 网格未完全显示。
  • x 轴也不完全显示。

有没有人可以完全显示这两个功能的解决方案?

这是我的图表的屏幕截图:

graph

这是数据:

data

这是我的代码:

x = msft_ebit_revenue_new['period'] 
y1 = msft_ebit_revenue_new['EBIT']
y2 = msft_ebit_revenue_new['Revenues']

绘制 Line1(左 Y 轴)

fig, ax1 = plt.subplots(1,1,figsize=(16,9), dpi= 80)
ax1.plot(x, y1, color='tab:red')

# 绘制 Line2(右 Y 轴)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
ax2.plot(x, y2, color='tab:blue')

装饰品

ax1(左 Y 轴)

ax1.set_xlabel('Period', fontsize=10)
ax1.tick_params(axis='x', rotation=0, labelsize=12)
ax1.set_ylabel('EBIT', color='tab:red', fontsize=20)
ax1.tick_params(axis='y', rotation=0, labelcolor='tab:red' )
ax1.grid(alpha=.4)

ax2(右 Y 轴)

ax2.set_ylabel("Revenues ($ in millions)", color='tab:blue', fontsize=20)
ax2.tick_params(axis='y', labelcolor='tab:blue')
ax2.set_xticks(np.arange(0, len(x), 60))
ax2.set_xticklabels(x[::60], rotation=90, fontdict={'fontsize':10})
ax2.set_title("EBIT vs Revenues (MSFT)", fontsize=22)
fig.tight_layout()
plt.show()

谢谢!

亚历克斯

【问题讨论】:

  • 问题似乎与以下几行有关: ax2.set_xticks(np.arange(0, len(x), 60)) ax2.set_xticklabels(x[::60], rotation=90 , fontdict={'fontsize':10})。在评论这些线网格变得可见。
  • 在这里,您正在配对 x 轴。 ax2 = ax1.twinx()。从而创建两个 y 轴。因此,在我看来,在这些条件下,定义两组不同的网格线和 x 轴会导致这个问题。

标签: python matplotlib


【解决方案1】:

问题

  • 显示 x 轴标签
  • 显示网格

解决方案

评论以下几行:

ax2.set_xticks(np.arange(0, len(x), 60))
ax2.set_xticklabels(x[::60], rotation=90, fontdict={'fontsize':10})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 2011-09-28
    • 2019-05-04
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    相关资源
    最近更新 更多