簡體   English   中英

在一張圖中繪制多條線,x 軸上以月為單位,y 軸上出現次數

[英]Plotting multiple lines in one graph with time in months on the x-axis, number of occurences on the y-axis

我目前正在研究一個電影數據集,我已將其過濾為每種類型每天的觀看次數。 我已將其過濾為數據框,如下所示:

我創建了一個包含 2 列(除了索引)的數據框,即'Date''Genre' 數據類型是datetime64[ns]'Genre'是一個object

為了形象化:

Date           Genre
2018-01-01     romance
2018-01-01     fiction
2018-01-01     romance
2018-01-02     drama
2018-01-02     romance
2018-01-02     fiction    
2018-01-02     romance
2018-01-03     romance
2018-01-03     drama

這個列表還在繼續(整個 2018 年),它表明,根據數據集,在 2018-01-01 上,已經觀看了三部電影, Genre浪漫、小說和浪漫。

題:

我想繪制一個多線圖,其中每條線代表不同的類型。 在 x 軸上,以月為單位顯示時間,在 y 軸上,將顯示手表的數量。 我想要做的是在同一個圖表中繪制每個流派,並顯示每天該流派的觀看次數,其中 x 軸以月為單位標記。

到目前為止我嘗試過的:

對每個流派的電影數據幀進行排序並將其存儲在一個新變量中:

df_2018_rom = df_movies_2018[df_movies_2018.Genre == 'romance']
.groupby(['Genre', 'Date']).Date.count()

但我似乎仍然無法繪制我想要的圖表。

提前感謝您的任何幫助!

您可以通過使用pandas.crosstab重塑您的DataFrame簡單地做到這pandas.crosstab

例子

# if needed - make sure 'Date' is correct dtype
df_movies_2018['Date'] = pd.to_datetime(df['Date'])

# Filter to genres you're interested in
genres_to_plot = ['romance', 'drama', 'fiction']
df = df_movies_2018[df_movies_2018.Genre.isin(genres_to_plot)]

df_cross = pd.crosstab(df.Date, df.Genre)
df_cross.plot()

在此處輸入圖片說明

作為參考, df_cross看起來像:

Genre       drama  fiction  romance
Date                               
2018-01-01      0        1        2
2018-01-02      1        1        2
2018-01-03      1        0        1

大熊貓DataFrame.plot方法將把在每一列DataFrame作為一個單獨的系列(線)與index為默認的x軸值。

暫無
暫無

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

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