我需要根據標簽創建分離圖。我的資料集是
Label Word Frequency
439 10.0 glass 600
471 10.0 tv 34
463 10.0 screen 31
437 10.0 laptop 15
454 10.0 info 15
65 -1.0 dog 1
68 -1.0 cat 1
69 -1.0 win 1
70 -2.0 man 1
71 -2.0 woman 1
在這種情況下,我希望繪制三幅圖,一幅畫 10 幅,一幅畫 -1,一幅畫 -2,x 軸是 Word 列,y 軸是頻率(它已經按標簽降序排序)。
我試過如下:
df['Word'].hist(by=df['Label'])
但這似乎是錯誤的,因為輸出與預期相差甚遠。
任何幫助都會很棒
uj5u.com熱心網友回復:
您不想在這里使用直方圖:直方圖是資料幀的列包含原始資料的地方,hist函式將原始值分桶并找出每個桶的頻率,然后進行繪圖。
您的資料框已經分桶,其中有一列已經計算了頻率;你需要的是df.plot.bar()方法。不幸的是,這是相當新的,并且還不允許使用by引數,因此您必須手動處理子圖。
您提供的縮減示例的完整演練代碼如下。顯然,您可以通過不對標記為 的行中所需的子圖數量進行硬編碼來使其更通用[1]。
# Set up:
import matplotlib.pyplot as plt
import pandas as pd
import io
txt = """Label,Word,Frequency
10.0,glass,600
10.0,tv,34
10.0,screen,31
10.0,laptop,15
10.0,info,15
-1.0,dog,1
-1.0,cat,1
-1.0,win,1
-2.0,man,1
-2.0,woman,1"""
dfA = pd.read_csv((io.StringIO(txt)))
labels = dfA["Label"].unique()
# Set up subplots on which to plot.
# Make more generic by not hardcoding nrows and ncols in [1],
# but calculating them depending on how many labels you have.
fig, axes = plt.subplots(nrows=2, ncols=2) # [1]
ax_list = axes.flatten() # axes is a list of lists;
# ax_list is a simple list which is easier to index.
# Loop through labels and plot the bar chart to the corresponding axis object.
for i in range(len(labels)):
dfA[dfA["Label"]==labels[i]].plot.bar(x="Word", y="Frequency", ax=ax_list[i])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344584.html
標籤:Python 熊猫 matplotlib
下一篇:我如何測驗這個功能?
