使用 twinx 时旋转 xtick 标签时出现问题

Problems rotating xtick labels when using twinx

我的 X 轴旋转有问题,我尝试无误地旋转输出图,但没有结果。

# Import Data
#df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv")
x = total_test["Dia"].values[:]; y1 = total_test["Confirmados"].values[:]; y2 = total_test["Fallecidos"].values[:]

# Plot Line1 (Left Y Axis)
fig, ax1 = plt.subplots(1,1,figsize=(10,8), dpi= 200)
ax1.plot(x, y1,'g^', color='tab:red')

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

# Just Decorations!! -------------------
# ax1 (left y axis)
ax1.set_xlabel('Dias', fontsize=10)
ax1.set_ylabel('Personas Confirmadas', color='tab:red', fontsize=20)
ax1.tick_params(axis='y', rotation=0, labelcolor='tab:red' )

# ax2 (right Y axis)
ax2.set_ylabel("Personas Fallecidas", color='tab:blue', fontsize=20)
ax2.tick_params(axis='y', rotation=0, labelcolor='tab:blue')
ax2.set_title("Personas Confirmadas y Fallecidas por Covid-19 Peru", fontsize=15)
#ax2.set_xticks(x)
ax2.set_xticklabels(x[::],fontsize=10,rotation=90)
plt.show()

  • x 轴的任何命令都需要在 ax2 之前发生。
  • 验证日期为 datetime 格式并设置为索引。
import pandas as pd
import matplotlib.pyplot as plt

# read data
df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv")

# verify the date column is a datetime format and set as index
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)

#plot
# create figure
fig, ax1 = plt.subplots(1, 1, figsize=(10,8))

# 1st plot
ax1.plot(df['pop'], color='tab:red')

# set xticks rotation before creating ax2
plt.xticks(rotation=90)

# 2nd plot (Right Y Axis)
ax2 = ax1.twinx()  # create the 'twin' axis on the right
ax2.plot(df['unemploy'], color='tab:blue')

plt.show()