Проблемы с поворотом этикеток xtick при использовании twinx - PullRequest
0 голосов
/ 04 мая 2020

У меня проблемы с вращением оси 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()

enter image description here

1 Ответ

1 голос
/ 05 мая 2020
  • Любые команды для оси 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()

enter image description here

...