我需要幫助從熊貓資料框中動態地在 matplotlib 中創建子圖。我使用的資料來自
我動態需要它的原因是因為我將動態應用過濾器(在 Power BI 中),并且我需要圖表來調整過濾器。
這是我到目前為止所擁有的:我匯入了資料并得到了我需要的形狀:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as
# read file from makeover monday year 2018 week 48
df = pd.read_csv(r'C:\Users\Ruth Pozuelo\Documents\python_examples\data\2018w48.csv', usecols=["city", "category","item", "cost"], index_col=False, decimal=",")
df.head()
這是表格:

然后我動態應用來自 Power BI 的篩選器:
df = df[df.category=='Party night']
然后我根據我應用過濾器后獲得的專案數來計算圖的數量:
itemCount = df['item'].nunique() #number of plots
如果我然后繪制子圖:
fig, ax = plt.subplots( nrows=1, ncols=itemCount ,figsize=(30,10), sharey=True)
我得到了骨架:

到目前為止,一切都很好!但是現在我對如何將 x 軸輸入到回圈中以生成子類別感到很困惑。我正在嘗試類似下面的東西,但沒有任何效果。
#for i, ax in enumerate(axes.flatten()):
# ax.plot(??,cityValues, marker='o',markersize=25, lw=0, color="green") # The top-left axes
因為我已經有了圖表的外觀和感覺、注釋等的代碼,所以我希望能夠使用 plt.subplots 方法,如果可能的話,我不喜歡使用 seaborn。
關于如何讓他作業的任何想法?
提前致謝!
uj5u.com熱心網友回復:
資料已呈現給我們,我們將其用作代碼的基礎。我準備了一個列串列和一個著色串列并遍歷它們。axes.rabel() 比 axes.fatten() 更節省記憶體。這是因為串列包含每個子圖的物件,允許集中配置。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
url='https://raw.githubusercontent.com/Curbal-Data-Labs/Matplotlib-Labs/master/2018w48.csv'
dataset = pd.read_csv(url)
dataset.drop_duplicates(['city','item'], inplace=True)
dataset.pivot_table(index='city', columns='item', values='cost', aggfunc='sum', margins = True).sort_values('All', ascending=True).drop('All', axis=1)
df = dataset.pivot_table(index='city', columns='item', values='cost', aggfunc='sum', margins = True).sort_values('All', ascending=True).drop('All', axis=1).sort_values('All', ascending=False, axis=1).drop('All').reset_index()
# comma replace
for c in df.columns[1:]:
df[c] = df[c].str.replace(',','.').astype(float)
fig, axes = plt.subplots(nrows=1, ncols=5, figsize=(30,10), sharey=True)
colors = ['green','blue','red','black','brown']
col_names = ['Dinner','Drinks at Dinner','2 Longdrinks','Club entry','Cinema entry']
for i, (ax,col,c) in enumerate(zip(axes.ravel(), col_names, colors)):
ax.plot(df.loc[:,col], df['city'], marker='o', markersize=25, lw=0, color=c)
ax.set_title(col)
for i,j in zip(df[col], df['city']):
ax.annotate('$' str(i), xy=(i, j), xytext=(i-4,j), color="white", fontsize=8)
ax.set_xticks([])
ax.spines[['top', 'right', 'left', 'bottom']].set_visible(False)
ax.grid(True, axis='y', linestyle='solid', linewidth=2)
ax.grid(True, axis='x', linestyle='solid', linewidth=0.2)
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')
ax.set_xlim(xmin=0, xmax=160)
ax.xaxis.set_major_formatter('${x:1.0f}')
ax.tick_params(labelsize=8, top=False, left=False)
plt.show()

uj5u.com熱心網友回復:
下面的作業示例。我使用 seaborn 來繪制條形圖,但想法是相同的,您可以回圈遍歷各個方面并增加計數。從 -1 開始,使您的第一個計數 = 0,并將其用作軸標簽。
import seaborn as sns
fig, ax = plt.subplots( nrows=1, ncols=itemCount ,figsize=(30,10), sharey=True)
df['Cost'] = df['Cost'].astype(float)
count = -1
variables = df['Item'].unique()
fig, axs = plt.subplots(1,itemCount , figsize=(25,70), sharex=False, sharey= False)
for var in variables:
count = 1
sns.barplot(ax=axs[count],data=df, x='Cost', y='City')
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517323.html
