首页 > 解决方案 > 在多轴图中旋转 xtick 标签

问题描述

我想在这个多轴图中旋转 xtick 标签(我用于单轴图的代码不起作用)。

在此处输入图像描述

xtick 标签应该是什么样子(忽略不同的日期) 在此处输入图像描述

编码

import numpy as np
import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1 import host_subplot
from mpl_toolkits import axisartist

# Create the data
data = {
    'Date': pd.date_range('2021-01-1', '2021-01-30'),
    'Close': np.linspace(100, 200, num=30) + np.random.normal(scale=10, size=30),
    'Volume': np.random.randint(500, 2000, size=30)
}
df = pd.DataFrame(data)
df = df.set_index(df.Date)

# Create the axis
plt.figure(figsize=(10,5))
host = host_subplot(111, axes_class=axisartist.Axes)
ax1 = host.twinx()
ax1.axis["right"].toggle(all=True)

# Plot the closing prices
line, = host.plot(df.index, df.Close, label="Close")
host.set_ylabel("Close")
host.yaxis.label.set_color(line.get_color())

# Plot the volumes
bar = ax1.bar(df.index, df.Volume, alpha=0.2, color='red', label="Volume")
ax1.set_ylabel('Volume')
ax1.yaxis.label.set_color('red')

host.legend()
plt.show()

该代码基于此 matplotlib 示例:
https ://matplotlib.org/stable/gallery/axisartist/demo_parasite_axes2.html#sphx-glr-gallery-axisartist-demo-parasite-axes2-py

单轴图的正常解决方案不起作用,例如。在 python matplotlib 中旋转轴文本

标签: pythonmatplotlib

解决方案


推荐阅读