python数据整理代码_熬夜整理的资料:分享Python数据可视化图表代码和案例给大家...
前言
本文的文字及圖片來源于網絡,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理。
閑話不多說,直接上干貨
1華夫餅圖
waffle可以使用該pywaffle軟件包創建該圖表,并用于顯示較大人群中各組的組成。
#! pip install pywaffle#Reference: https://stackoverflow.com/questions/41400136/how-to-do-waffle-charts-in-python-square-piechart
from pywaffle importWaffle#Import
df_raw = pd.read_csv("data/mpg_ggplot2.csv")#Prepare Data
df = df_raw.groupby('class').size().reset_index(name='counts')
n_categories=df.shape[0]
colors= [plt.cm.inferno_r(i/float(n_categories)) for i inrange(n_categories)]#Draw Plot and Decorate
fig =plt.figure(
FigureClass=Waffle,
plots={'111': {'values': df['counts'],'labels': ["{0} ({1})".format(n[0], n[1]) for n in df[['class', 'counts']].itertuples()],'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12},'title': {'label': '# Vehicles by Class', 'loc': 'center', 'fontsize':18}
},
},
rows=7,
colors=colors,
figsize=(16, 9)
)
#! pip install pywaffle
from pywaffle importWaffle#Import#df_raw = pd.read_csv("data/mpg_ggplot2.csv")
#Prepare Data#By Class Data
df_class = df_raw.groupby('class').size().reset_index(name='counts_class')
n_categories=df_class.shape[0]
colors_class= [plt.cm.Set3(i/float(n_categories)) for i inrange(n_categories)]#By Cylinders Data
df_cyl = df_raw.groupby('cyl').size().reset_index(name='counts_cyl')
n_categories=df_cyl.shape[0]
colors_cyl= [plt.cm.Spectral(i/float(n_categories)) for i inrange(n_categories)]#By Make Data
df_make = df_raw.groupby('manufacturer').size().reset_index(name='counts_make')
n_categories=df_make.shape[0]
colors_make= [plt.cm.tab20b(i/float(n_categories)) for i inrange(n_categories)]#Draw Plot and Decorate
fig =plt.figure(
FigureClass=Waffle,
plots={'311': {'values': df_class['counts_class'],'labels': ["{1}".format(n[0], n[1]) for n in df_class[['class', 'counts_class']].itertuples()],'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Class'},'title': {'label': '# Vehicles by Class', 'loc': 'center', 'fontsize':18},'colors': colors_class
},'312': {'values': df_cyl['counts_cyl'],'labels': ["{1}".format(n[0], n[1]) for n in df_cyl[['cyl', 'counts_cyl']].itertuples()],'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Cyl'},'title': {'label': '# Vehicles by Cyl', 'loc': 'center', 'fontsize':18},'colors': colors_cyl
},'313': {'values': df_make['counts_make'],'labels': ["{1}".format(n[0], n[1]) for n in df_make[['manufacturer', 'counts_make']].itertuples()],'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Manufacturer'},'title': {'label': '# Vehicles by Make', 'loc': 'center', 'fontsize':18},'colors': colors_make
}
},
rows=9,
figsize=(16, 14)
)
2 餅圖
餅圖是顯示組組成的經典方法。但是,如今一般不建議使用它,因為餡餅部分的面積有時可能會引起誤解。因此,如果要使用餅圖,強烈建議明確寫下餅圖各部分的百分比或數字。
#Import
df_raw = pd.read_csv("data/mpg_ggplot2.csv")#Prepare Data
df = df_raw.groupby('class').size()#Make the plot with pandas
df.plot(kind='pie', subplots=True, figsize=(8, 8), dpi= 80)
plt.title("Pie Chart of Vehicle Class - Bad")
plt.ylabel("")
plt.show()
#Import
df_raw = pd.read_csv("data/mpg_ggplot2.csv")#Prepare Data
df = df_raw.groupby('class').size().reset_index(name='counts')#Draw Plot
fig, ax = plt.subplots(figsize=(12, 7), subplot_kw=dict(aspect="equal"), dpi= 80)
data= df['counts']
categories= df['class']
explode= [0,0,0,0,0,0.1,0]deffunc(pct, allvals):
absolute= int(pct/100.*np.sum(allvals))return "{:.1f}% ({:d} )".format(pct, absolute)
wedges, texts, autotexts=ax.pie(data,
autopct=lambdapct: func(pct, data),
textprops=dict(color="w"),
colors=plt.cm.Dark2.colors,
startangle=140,
explode=explode)#Decoration
ax.legend(wedges, categories, title="Vehicle Class", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))
plt.setp(autotexts, size=10, weight=700)
ax.set_title("Class of Vehicles: Pie Chart")
plt.show()
3 樹狀圖
樹形圖類似于餅形圖,并且可以更好地完成工作,而不會誤導每個組的貢獻。
#pip install squarify
importsquarify#Import Data
df_raw = pd.read_csv("data/mpg_ggplot2.csv")#Prepare Data
df = df_raw.groupby('class').size().reset_index(name='counts')
labels= df.apply(lambda x: str(x[0]) + "n (" + str(x[1]) + ")", axis=1)
sizes= df['counts'].values.tolist()
colors= [plt.cm.Spectral(i/float(len(labels))) for i inrange(len(labels))]#Draw Plot
plt.figure(figsize=(12,8), dpi= 80)
squarify.plot(sizes=sizes, label=labels, color=colors, alpha=.8)#Decorate
plt.title('Treemap of Vechile Class')
plt.axis('off')
plt.show()
4 條形圖
條形圖是一種基于計數或任何給定指標可視化項目的經典方法。在下面的圖表中,我為每個項目使用了不同的顏色,但是您通常可能希望為所有項目選擇一種顏色,除非您按組對它們進行著色。顏色名稱存儲在all_colors下面的代碼中。您可以通過在中設置color參數來更改條形的顏色。
importrandom#Import Data
df_raw = pd.read_csv("data/mpg_ggplot2.csv")#Prepare Data
df = df_raw.groupby('manufacturer').size().reset_index(name='counts')
n= df['manufacturer'].unique().__len__()+1all_colors=list(plt.cm.colors.cnames.keys())
random.seed(100)
c= random.choices(all_colors, k=n)#Plot Bars
plt.figure(figsize=(16,10), dpi= 80)
plt.bar(df['manufacturer'], df['counts'], color=c, width=.5)for i, val in enumerate(df['counts'].values):
plt.text(i, val, float(val), horizontalalignment='center', verticalalignment='bottom', fontdict={'fontweight':500, 'size':12})#Decoration
plt.gca().set_xticklabels(df['manufacturer'], rotation=60, horizontalalignment= 'right')
plt.title("Number of Vehicles by Manaufacturers", fontsize=22)
plt.ylabel('# Vehicles')
plt.ylim(0,45)
plt.show()
不管你是零基礎還是有基礎都可以獲取到自己相對應的學習禮包!包括Python軟件工具和2020最新入門到實戰教程。加群695185429即可免費獲取。
內容來源于網絡如有侵權請私信刪除
總結
以上是生活随笔為你收集整理的python数据整理代码_熬夜整理的资料:分享Python数据可视化图表代码和案例给大家...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电信充q币短信怎么发_王者荣耀充值中心Q
- 下一篇: formdata传递参数_前端利用for