這里放上我比較喜歡的一種條形圖設置,使用的是之前爬取的重慶地區鏈家二手房數據,數據如下:
鏈接:https://pan.baidu.com/s/17CMwUAdseO8tJWHEQiA8_A
提取碼:dl2g
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv('lianjia_utf.csv') df.head()
sns.set(style='white', font_scale=1.2) # 保證可以顯示中文字體 plt.rcParams['font.sans-serif']='simhei' # 設置字體大小 font1 = {'family' : 'simhei', 'weight' : 'normal', 'size' : 18,} # 使用數據透視表 region_pivot = pd.pivot_table(df, values='Price', index='Region', aggfunc='count').reset_index().sort_values(ascending=True,by='Price') f, ax = plt.subplots(figsize=(8,6)) # 畫條形圖 barh = plt.barh(region_pivot['Region'].values,region_pivot['Price'].values, color='dodgerblue') barh[-1].set_color('green') # 給條形圖添加數據標注 for y, x in enumerate(region_pivot['Price'].values): plt.text(x+500, y-0.2, "%s" %x) #刪除所有邊框 ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) # ax.set(title='重慶各區域二手房總價', xlabel='地區', ylabel='總價') plt.tick_params(labelsize=14) plt.xlabel('地區', font1) plt.ylabel('總價', font1) plt.title('重慶各區域二手房總價', font1) f.savefig('1.png', bbox_inches='tight')
運行結果如下:
如果把上圖改成柱形圖,可以這樣做:
sns.set(style='white', font_scale=1.2) # 保證可以顯示中文字體 plt.rcParams['font.sans-serif']='simhei' # 設置字體大小 font1 = {'family' : 'simhei', 'weight' : 'normal', 'size' : 18,} # 使用數據透視表 region_pivot = pd.pivot_table(df, values='Price', index='Region', aggfunc='count').reset_index().sort_values(ascending=False,by='Price') f, ax = plt.subplots(figsize=(12,6)) # 畫柱形圖 bar = plt.bar(region_pivot['Region'].values,region_pivot['Price'].values, color='dodgerblue') bar[0].set_color('green') # 給條形圖添加數據標注 for x, y in enumerate(region_pivot['Price'].values): plt.text(x-0.4, y+500, "%s" %y) #刪除所有邊框 ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) # ax.set(title='重慶各區域二手房總價', xlabel='地區', ylabel='總價') plt.tick_params(labelsize=14) plt.xlabel('地區', font1) plt.ylabel('總價', font1) plt.title('重慶各區域二手房總價', font1) f.savefig('1_1.png', bbox_inches='tight')
運行結果如下:
關於配色,matplotlib中的配色,可參考下圖: