目錄
表格風格圖
使用Seaborn函數繪圖
設置圖表風格
設置顏色主題
圖表分面
繪圖過程
使用繪圖函數繪圖
定義主題
分面1
分面2
【聲明】:未經版權人書面許可,任何單位或個人不得以任何形式復制、發行、出租、改編、匯編、傳播、展示或利用本博客的全部或部分內容,也不得在未經版權人授權的情況下將本博客用于任何商業目的。但版權人允許個人學習、研究、欣賞等非商業性用途的復制和傳播。非常推薦大家學習《Python數據可視化科技圖表繪制》這本書籍。
表格風格圖
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as mcolors
from matplotlib.patches import Rectanglenp.random.seed(19781101) # 固定隨機種子,以便結果可復現def plot_scatter(ax,prng,nb_samples=100):"""繪制散點圖"""for mu,sigma,marker in [(-.5,0.75,'o'),(0.75,1.,'s')]:x,y=prng.normal(loc=mu,scale=sigma,size=(2,nb_samples))ax.plot(x,y,ls='none',marker=marker)ax.set_xlabel('X-label')ax.set_title('Axes title')return axdef plot_colored_lines(ax):"""繪制顏色循環線條"""t=np.linspace(-10,10,100)def sigmoid(t,t0):return 1/(1+np.exp(-(t-t0)))nb_colors=len(plt.rcParams['axes.prop_cycle'])shifts=np.linspace(-5,5,nb_colors)amplitudes=np.linspace(1,1.5,nb_colors)for t0,a in zip(shifts,amplitudes):ax.plot(t,a*sigmoid(t,t0),'-')ax.set_xlim(-10,10)return axdef plot_bar_graphs(ax,prng,min_value=5,max_value=25,nb_samples=5):"""繪制兩個并排的柱狀圖。"""x=np.arange(nb_samples)ya,yb=prng.randint(min_value,max_value,size=(2,nb_samples))width=0.25ax.bar(x,ya,width)ax.bar(x+width,yb,width,color='C2')ax.set_xticks(x+width,labels=['a','b','c','d','e'])return axdef plot_colored_circles(ax,prng,nb_samples=15):"""繪制彩色圓形。"""for sty_dict,j in zip(plt.rcParams['axes.prop_cycle'](),range(nb_samples)):ax.add_patch(plt.Circle(prng.normal(scale=3,size=2),radius=1.0,color=sty_dict['color']))ax.grid(visible=True)# 添加標題以啟用網格plt.title('ax.grid(True)',family='monospace',fontsize='small')ax.set_xlim([-4,8])ax.set_ylim([-5,6])ax.set_aspect('equal',adjustable='box') # 繪制圓形return axdef plot_image_and_patch(ax,prng,size=(20,20)):"""繪制圖像和圓形補丁。"""values=prng.random_sample(size=size)ax.imshow(values,interpolation='none')c=plt.Circle((5,5),radius=5,label='patch')ax.add_patch(c)# 移除刻度ax.set_xticks([])ax.set_yticks([])def plot_histograms(ax,prng,nb_samples=10000):"""繪制四個直方圖和一個文本注釋。"""params=((10,10),(4,12),(50,12),(6,55))for a,b in params:values=prng.beta(a,b,size=nb_samples)ax.hist(values,histtype="stepfilled",bins=30,alpha=0.8,density=True)# 添加小注釋。ax.annotate('Annotation',xy=(0.25,4.25),xytext=(0.9,0.9),textcoords=ax.transAxes,va="top",ha="right",bbox=dict(boxstyle="round",alpha=0.2),arrowprops=dict(arrowstyle="->",connectionstyle="angle,angleA=-95,angleB=35,rad=10"),)return axdef plot_figure(style_label=""):"""設置并繪制具有給定樣式的演示圖。"""# 在不同的圖之間使用專用的RandomState實例繪制相同的“隨機”值prng=np.random.RandomState(96917002)# 創建具有特定樣式的圖和子圖fig,axs=plt.subplots(ncols=6,nrows=1,num=style_label,figsize=(14.8,2.8),layout='constrained')# 添加統一的標題,標題顏色與背景顏色相匹配background_color=mcolors.rgb_to_hsv(mcolors.to_rgb(plt.rcParams['figure.facecolor']))[2]if background_color<0.5:title_color=[0.8,0.8,1]else:title_color=np.array([19,6,84])/256fig.suptitle(style_label,x=0.01,ha='left',color=title_color,fontsize=14,fontfamily='DejaVu Sans',fontweight='normal')plot_scatter(axs[0],prng)plot_image_and_patch(axs[1],prng)plot_bar_graphs(axs[2],prng)plot_colored_lines(axs[3])plot_histograms(axs[4],prng)plot_colored_circles(axs[5],prng)# 添加分隔線rec=Rectangle((1+0.025,-2),0.05,16,clip_on=False,color='gray')axs[4].add_artist(rec)# 保存圖片plt.savefig(f'{style_label}.png', dpi=600)plt.close(fig) # 關閉當前圖形以避免內存占用過多if __name__=="__main__":# 獲取所有可用的樣式列表,按字母順序排列style_list=['default','classic']+sorted(style for style in plt.style.availableif style !='classic' and not style.startswith('_'))# 繪制每種樣式的演示圖for style_label in style_list:with plt.rc_context({"figure.max_open_warning":len(style_list)}):with plt.style.context(style_label):plot_figure(style_label=style_label)plt.show()



























使用Seaborn函數繪圖
import seaborn as sns
import matplotlib.pyplot as plt# 加載數據集
iris=sns.load_dataset("iris",data_home='seaborn-data',cache=True)
tips=sns.load_dataset("tips",data_home='seaborn-data',cache=True)
car_crashes=sns.load_dataset("car_crashes",data_home='seaborn-data',cache=True)
penguins=sns.load_dataset("penguins",data_home='seaborn-data',cache=True)
diamonds=sns.load_dataset("diamonds",data_home='seaborn-data',cache=True)plt.figure(figsize=(15,8)) # 設置畫布
# 第1幅圖:iris數據集的散點圖
plt.subplot(2,3,1)
sns.scatterplot(x="sepal_length",y="sepal_width",hue="species",data=iris)
plt.title("Iris scatterplot")# 第2幅圖:tips 數據集的箱線圖
plt.subplot(2,3,2)
tips=sns.load_dataset("tips",data_home='seaborn-data',cache=True)
sns.boxplot(x="day",y="total_bill",hue="smoker",data=tips)
plt.title("Tips boxplot")# 第3幅圖:tips 數據集的小提琴圖
plt.subplot(2,3,3)
sns.violinplot(x="day",y="total_bill",hue="smoker",data=tips)
plt.title("Tips violinplot")# 第4幅圖:car_crashes 數據集的直方圖
plt.subplot(2,3,4)
sns.histplot(car_crashes['total'],bins=20)
plt.title("Car Crashes histplot")# 第5幅圖:penguins 數據集的點圖
plt.subplot(2,3,5)
sns.pointplot(x="island",y="bill_length_mm",hue="species",data=penguins)
plt.title("Penguins pointplot")# 第6幅圖:diamonds 數據集的計數圖
plt.subplot(2,3,6)
sns.countplot(x="cut",data=diamonds)
plt.title("Diamonds countplot")plt.tight_layout()# 保存圖片
plt.savefig('P75使用Seaborn函數繪圖.png', dpi=600, transparent=True)
plt.show()

設置圖表風格
import seaborn as sns
import matplotlib.pyplot as pltsns.set_style("darkgrid") # 設置圖表風格為 darkgrid
iris=sns.load_dataset("iris") # 加載 iris 數據集# 繪制花瓣長度與寬度的散點圖
sns.scatterplot(x="petal_length",y="petal_width",hue="species",data=iris)
plt.title("Scatter Plot of Petal Length vs Petal Width")# 保存圖片
plt.savefig('P77設置圖表風格.png', dpi=600, transparent=True)
plt.show()

設置顏色主題
import seaborn as sns
import matplotlib.pyplot as pltsns.set_palette("deep") # 設置顏色主題為deep
tips=sns.load_dataset("tips") # 加載 tips 數據集# 繪制小費金額的小提琴圖,按照就餐日期和吸煙者區分顏色
sns.violinplot(x="day",y="total_bill",hue="smoker",data=tips)
plt.title("Tips violinplot") # 設置圖表標題# 保存圖片
plt.savefig('P78設置顏色主題.png', dpi=600, transparent=True)
plt.show()

圖表分面
import seaborn as sns
import matplotlib.pyplot as pltiris=sns.load_dataset("iris") # 加載iris數據集# 創建 FacetGrid 對象,按照種類('species')進行分面
g=sns.FacetGrid(iris,col="species",margin_titles=True)
# 在每個子圖中繪制花萼長度與花萼寬度的散點圖
g.map(sns.scatterplot,"sepal_length","sepal_width")
g.set_axis_labels("Sepal Length","Sepal Width") # 設置子圖標題# 保存圖片
plt.savefig('P80圖表分面.png', dpi=600, transparent=True)
plt.show()

繪圖過程
from plotnine import *
import seaborn as sns
import warnings# 忽略 PlotnineWarning
warnings.filterwarnings("ignore", category=UserWarning, module="plotnine")# 加載數據集
penguins = sns.load_dataset("penguins", data_home='seaborn-data', cache=True)# 檢查并處理缺失值
penguins = penguins.dropna()# 創建畫布和導入數據
p = ggplot(penguins, aes(x='bill_length_mm', y='bill_depth_mm', color='species'))# 添加幾何對象圖層-散點圖,并進行美化
p = p + geom_point(size=3, alpha=0.7)# 設置標度
p = p + scale_x_continuous(name='Length (mm)')
p = p + scale_y_continuous(name='Depth (mm)')# 設置主題和其他參數
p = p + theme(legend_position='top', figure_size=(6, 4))# 保存繪圖
ggsave(p, filename="P82繪圖過程.png", width=6, height=4, dpi=600)

使用繪圖函數繪圖
import warnings
from plotnine import *
from plotnine.data import *# 忽略 PlotnineWarning
warnings.filterwarnings("ignore", category=UserWarning, module="plotnine")# 散點圖-mpg 數據集
p1 = (ggplot(mpg) +aes(x='displ', y='hwy') +geom_point(color='blue') +labs(title='Displacement vs Highway MPG') +theme(plot_title=element_text(size=14, face='bold')))# 箱線圖-diamonds 數據集
p2 = (ggplot(diamonds.sample(1000)) +aes(x='cut', y='price', fill='cut') +geom_boxplot() +labs(title='Diamond Price by Cut') +scale_fill_brewer(type='qual', palette='Pastel1') +theme(plot_title=element_text(size=14, face='bold')))# 直方圖-msleep 數據集
p3 = (ggplot(msleep) +aes(x='sleep_total') +geom_histogram(bins=20, fill='green', color='black') +labs(title='Total Sleep in Mammals') +theme(plot_title=element_text(size=14, face='bold')))# 線圖-economics 數據集
p4 = (ggplot(economics) +aes(x='date', y='unemploy') +geom_line(color='red') +labs(title='Unemployment over Time') +theme(plot_title=element_text(size=14, face='bold')))# 條形圖-presidential 數據集
presidential['duration'] = (presidential['end'] - presidential['start']).dt.days
p5 = (ggplot(presidential) +aes(x='name', y='duration', fill='name') +geom_bar(stat='identity') +labs(title='Presidential Terms Duration') +scale_fill_hue(s=0.90, l=0.65) +theme(axis_text_x=element_text(rotation=90, hjust=1),plot_title=element_text(size=14, face='bold')))# 折線圖-midwest 數據集
p6 = (ggplot(midwest) +aes(x='area', y='popdensity') +geom_line(color='purple') +labs(title='Population Density vs Area') +theme(plot_title=element_text(size=14, face='bold')))# 保存圖片
plots = [p1, p2, p3, p4, p5, p6]
plot_names = ['scatter_plot', 'boxplot', 'histogram', 'line_plot', 'bar_plot', 'line_chart']for plot, name in zip(plots, plot_names):plot.save(f'P85使用繪圖函數繪圖_{name}.png', width=8, height=6, dpi=600, transparent=True)






定義主題
from plotnine import *
from plotnine.data import mpg# 創建散點圖
p = (ggplot(mpg, aes(x='displ', y='hwy', color='displ')) +geom_point() + # 添加點圖層scale_color_gradient(low='blue', high='red') + # 設置顏色漸變labs(title='Engine Displacement vs. Highway MPG', # 設置圖表標題x='Engine Displacement (L)', # 設置x軸標題y='Miles per Gallon (Highway)') + # 設置y軸標題theme_minimal() + # 使用最小主題theme(axis_text_x=element_text(angle=45, hjust=1), # 自定義x軸文字樣式axis_text_y=element_text(color='darkgrey'), # 自定義y軸文字樣式plot_background=element_rect(fill='whitesmoke'), # 自定義圖表背景色panel_background=element_rect(fill='white', color='black', size=0.5), # 自定義面板背景和邊框panel_grid_major=element_line(color='lightgrey'), # 自定義主要網格線顏色panel_grid_minor=element_line(color='lightgrey', linestyle='--'), # 自定義次要網格線樣式legend_position='right', # 設置圖例位置figure_size=(8, 6))) # 設置圖形大小# 保存圖片
p.save('P88定義主題.png', dpi=600, transparent=True)# 顯示圖形
print(p)

分面1
from plotnine import *
from plotnine.data import mpg# 創建散點圖并按照`class`變量進行分面,添加顏色漸變
p = (ggplot(mpg, aes(x='displ', y='hwy', color='displ')) +geom_point() +scale_color_gradient(low='blue', high='orange') + # 添加顏色漸變facet_wrap('~class') + # 按照汽車類型分面labs(title='Engine Displacement vs. Highway MPG by Vehicle Class',x='Engine Displacement (L)',y='Miles per Gallon (Highway)'))# 保存圖片
p.save('P89分面1.png', dpi=600, transparent=True)# 顯示圖片
p.draw()

分面2
from plotnine import *
from plotnine.data import mpg# 創建散點圖并按照class變量進行分面,根據drv變量映射顏色
p=(ggplot(mpg,aes(x='displ',y='hwy',color='drv'))+geom_point()+ # 添加點圖層scale_color_brewer(type='qual',palette='Set1')+ # 使用定性的顏色方案facet_grid('drv ~ class')+ # 行是驅動類型,列是汽車類型labs(title='Engine Displacement vs. Highway MPG by Vehicle Class',x='Engine Displacement (L)',y='Miles per Gallon (Highway)')+theme_light()+ # 使用亮色主題theme(figure_size=(10,6), # 調整圖形大小strip_text_x=element_text(size=10,color='black',angle=0),# 自定義分面標簽的樣式legend_title=element_text(color='blue',size=10),# 自定義圖例標題的樣式legend_text=element_text(size=8), # 自定義圖例文本的樣式legend_position='right')) # 調整圖例位置# 保存圖片
p.save('P90分面2.png', dpi=600, transparent=True)# 顯示圖片
p.draw()
