簡體   English   中英

折線圖X軸移位起點position

[英]Shifting start position of X Axis of line chart

我想將紅線的起點 position 從“FEB-2020”移到“JAN-2021”。 目前這是我的代碼和我當前output的圖片。基本上將整個圖表的周期縮短為上述日期。

# plot daily vaccinated
fig, ax1= plt.subplots(1,figsize=(20,10))
# set up
plt.ticklabel_format(style='plain') #changing the tick figure from le 6 to millions
plt.setp(ax1, xticks= np.arange(0, 680, 30), xticklabels=vac_dates)
# plot chart
ax1.plot(vaccinated['received_at_least_one_dose'], label= 'Total Vaccinated', c='Red')
# axis and legend settings
ax1.set_ylabel('population (millions)', size= 14)
ax1.set_title('Monthly Vaccinated Numbers', size= 20)
plt.xticks(rotation=45)
plt.grid()

ax1.legend(loc="upper left")
##########################################################
# plot daily covid cases
ax2 = ax1.twinx()

# np.arrange looks at the number of rows
plt.setp(ax2, xticks= np.arange(0, 1035, 31), xticklabels=dates)
ax2.xaxis.tick_top()
ax2.plot(infected_update)

plt.xlabel('date', fontsize=14)
plt.ylabel('population (thousands)', fontsize=14)
 
plt.grid(False)

ax2.legend(['imported','local'], loc="upper right")

代碼輸出

我試過使用來自以下鏈接的代碼,但它似乎不起作用

https://stackoverflow.com/questions/29370057/select-dataframe-rows-between-two-dates

https://stackoverflow.com/questions/32434607/how-to-shift-a-graph-along-the-x-axis

這是一個非常基本的示例,使用 pandas、日期時間索引和 matplotlib。 確保索引的類型很重要DatetimeIndex

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'a':[3,4,5]}, index=pd.date_range('2020-01-03', '2020-01-05', freq='D'))
df_2 = pd.DataFrame({'b':[1,2,3,4,5], 'c':[1,2,2,2,2]}, index=pd.date_range('2020-01-01', '2020-01-05', freq='D'))

# plot daily vaccinated
fig, ax1= plt.subplots(1,figsize=(10,5))
# set up
ax1.plot(df.index, df['a'], label= 'Total Vaccinated', c='Red')
# axis and legend settings
ax1.set_ylabel('population (millions)', size= 14)
ax1.set_title('Monthly Vaccinated Numbers', size= 20)
plt.xticks(rotation=45)
plt.grid()

ax1.legend(loc="upper left")

##########################################################
# plot daily covid cases
ax2 = ax1.twinx()

# np.arrange looks at the number of rows
ax2.xaxis.tick_top()
ax2.plot(df_2.index, df_2['b'], color='Orange')

plt.xlabel('date', fontsize=14)
plt.ylabel('population (thousands)', fontsize=14)

plt.grid(False)

日期時間基准線圖

這意味着在您的情況下,您必須確保在讀取數據時設置parse_dates=True並設置索引。 使用pd.read_csv()這看起來像

df = pd.read_csv('covid.csv', sep=',', parse_dates=True, index_col=0)

因為你必須使用 DataFrame,所以你必須確保兩者都有一個 DatetimeIndex。 之后只需將兩次調用中的列替換為ac.plot()

評論:

如果你想要 plot Dataframe 的所有列, ax2.plot(df_2.index, df_2)有效。 如果你想要 select 列的子集ax2.plot(df_2.index, df_2[['b', 'c']])正在做這項工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM