【學習】python畫圖總結

一、基礎

一般畫圖的邏輯包括:

  • 圖片大小
  • 是否分圖
  • 圖表形式(什么圖、里面的畫線格式等)
  • 圖標題
  • 橫縱坐標軸
  • 橫縱坐標刻度
  • 圖例
  • 網(wǎng)格
  • 顏色
  • text
1.1 基礎設置

http://www.itdecent.cn/p/9cddc1a3e43f

plt.figure(figsize=(10,6)) #設置圖表大小

# 畫圖
x = range(11)
y1 = np.arange(0,1.1,0.1)
y2 = np.arange(0,2.1,0.2)

plt.plot(x,y1,label='y1')
plt.plot(x,y2,label='y2',linestyle='--')

#label設置
plt.title('Interesting Graph - Check it out')  # 圖名
plt.xlabel('Plot Number')  # x軸標簽
plt.ylabel('Important var') # y軸標簽
plt.legend(loc = 'upper right')  # 顯示圖例,loc表示位置
# 'best'         : 0, (only implemented for axes legends)(自適應方式)
# 'upper right'  : 1,
# 'upper left'   : 2,
# 'lower left'   : 3,
# 'lower right'  : 4,
# 'right'        : 5,
# 'center left'  : 6,
# 'center right' : 7,
# 'lower center' : 8,
# 'upper center' : 9,
# 'center'       : 10,

# lim和ticks會互相覆蓋,最終的尺度會以最后一個設置為標準
plt.xticks(range(11),labels=["%.1f" %i for i in range(11)],rotation = 90)  # 設置x刻度和標簽,旋轉(zhuǎn)角度
plt.yticks([0,0.2,0.4,0.6,0.8,1.0,1.2])  # 設置y刻度
plt.xlim([0,10])  # x軸邊界
plt.ylim([0,1])  # y軸邊界


# 刻度顯示
plt.tick_params(axis='x',which = 'major',direction='in', length=6, width=2, colors='black')  
plt.tick_params(axis='y',direction='out', length=6, width=2, colors='black')  


# 顯示網(wǎng)格
# linestyle:線型
# color:顏色
# linewidth:寬度
# axis:x,y,both,顯示x/y/兩者的格網(wǎng)
plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'both') 

# 顯示圖標
plt.text(x=5, y=0.5,s='text',ha='center', va='center',fontsize=15, rotation=90)
image.png

如果要設置主刻度和次刻度,比較麻煩,必須配合matplotlib.ticker使用。最終的參數(shù)用plt.tick_params來設置顯示格式

from matplotlib.ticker import MultipleLocator, FormatStrFormatter

xmajorLocator = MultipleLocator(0.5) # 將x主刻度標簽設置為10的倍數(shù)
xmajorFormatter = FormatStrFormatter('%.1f') # 設置x軸標簽文本的格式
xminorLocator   = MultipleLocator(0.1) # 將x軸次刻度標簽設置為5的倍數(shù)  
ymajorLocator = MultipleLocator(0.1) # 將y軸主刻度標簽設置為0.5的倍數(shù)
ymajorFormatter = FormatStrFormatter('%.1f') # 設置y軸標簽文本的格式
yminorLocator   = MultipleLocator(0.1) # 將此y軸次刻度標簽設置為0.1的倍數(shù)  

# plt.gca()也可以用ax1來代替
plt.gca().xaxis.set_major_locator(xmajorLocator)  # 設置x軸主刻度
plt.gca().xaxis.set_major_formatter(xmajorFormatter)  # 設置x軸標簽文本格式
plt.gca().xaxis.set_minor_locator(xminorLocator)  # 設置x軸次刻度

plt.gca().yaxis.set_major_locator(ymajorLocator)  # 設置y軸主刻度
plt.gca().yaxis.set_major_formatter(ymajorFormatter)  # 設置y軸標簽文本格式
plt.gca().yaxis.set_minor_locator(yminorLocator)  # 設置y軸次刻度

plt.gca().xaxis.grid(True, which='major') #x坐標軸的網(wǎng)格使用主刻度
plt.gca().xaxis.grid(True, which='minor') #x坐標軸的網(wǎng)格使用主刻度
plt.gca().yaxis.grid(True, which='minor') #y坐標軸的網(wǎng)格使用次刻度
plt.gca().yaxis.grid(True, which='major') #y坐標軸的網(wǎng)格使用次刻度
image.png
1.2 多圖

https://www.cnblogs.com/yymn/p/9479666.html

x= np.linspace(0,2*np.pi,500)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x*x)

plt.figure(figsize=(10,6)) #設置圖表大小
ax1 = plt.subplot(2,2,1)
ax2 = plt.subplot(2,2,2)
ax3 = plt.subplot(2,1,2)

# 選擇ax1
plt.sca(ax1)
plt.plot(x,y1,color='red')
plt.title('Graph1')  # 圖名

# 選擇ax2
plt.sca(ax2)
plt.plot(x,y2,color='blue',linestyle='--')
plt.title('Graph2')  # 圖名

# 選擇ax3
plt.sca(ax3)
plt.plot(x,y3,'g--',label='y3')
plt.title('Graph3')  # 圖名
plt.legend()
image.png
1.3 顏色

https://www.cnblogs.com/qianblue/p/10783261.html

image.png

自己搭的10色系

colors =['lightcoral', 'lightseagreen', 'cornflowerblue', 'orange','dodgerblue', 'tomato','mediumslateblue', 'gold',  'dimgray', 'peru']
plt.figure(figsize=(10,6))
plt.bar(range(10),range(1,11),color= colors)
image.png

二、常用圖(基于seaborn)

https://blog.csdn.net/qq_40195360/article/details/86605860

  • 直線圖
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='darkgrid')
# Seaborn有五個預設好的主題: darkgrid , whitegrid , dark , white ,和 ticks 默認: darkgrid
# 用默認的格式可能存在不顯示ticks的問題,如果要顯示ticks,最好不要用預設主題

plt.figure(figsize=(10,6))
plt.hlines(5,0,10)
plt.vlines(5,0,10)
plt.xticks(range(11))  

plt.xlim(0,10)
plt.ylim(0,10)
image.png
  • 柱狀圖
plt.figure(figsize=(15,12))
ax1 = plt.subplot(2,2,1)
ax2 = plt.subplot(2,2,2)
ax3 = plt.subplot(2,1,2)


# 一般柱狀圖
plt.sca(ax1)
bar_width = 0.8
plt.bar(range(5),range(1,6),color= colors,width=bar_width)
plt.xticks(ticks=range(5), labels=('A','B','C','D','E'))
for i in range(5): #顯示數(shù)值
    plt.text(i,i+1.1,i+1,ha='center', va='center',fontsize=15,)

# 雙柱狀圖
plt.sca(ax2)
bar_width = 0.4
plt.bar(np.arange(5)-bar_width/2,range(1,6),color='skyblue',width=bar_width,label='y1')
plt.bar(np.arange(5)+bar_width/2,range(4,9),color='orange',width=bar_width,label='y2')
plt.xticks(ticks=range(5), labels=('A','B','C','D','E'))
plt.legend()

for i in range(5): #顯示數(shù)值
    plt.text(i-bar_width/2,i+1.2,i+1,ha='center', va='center',fontsize=15,)
    plt.text(i+bar_width/2,i+4.2,i+4,ha='center', va='center',fontsize=15,)
    
# 疊加柱狀圖
plt.sca(ax3)
bar_width = 0.8
plt.bar(np.arange(5),range(4,9),color='orange',width=bar_width,label='y2',alpha=0.5)
plt.bar(np.arange(5),range(1,6),color='skyblue',width=bar_width,label='y1',alpha=0.5)
plt.xticks(ticks=range(5), labels=('A','B','C','D','E'))
plt.legend()

for i in range(5): #顯示數(shù)值
    plt.text(i,i+1.2,i+1,ha='center', va='center',fontsize=15,)
    plt.text(i,i+4.2,i+4,ha='center', va='center',fontsize=15,)
image.png
  • 折線圖
plt.figure(figsize=(10,6))
plt.plot(range(5),range(1,6),marker='^',linestyle='--',label='y1')
plt.plot(range(5),range(6,1,-1),marker='*',linestyle='-.',label='y2')
plt.legend()
image.png
  • 餅圖
plt.figure(figsize=(10,10))
plt.pie([1,2,4,5,4],explode=[0.1,0,0.1,0,0],colors=colors,autopct='%1.1f%%',labels=['A','B','C','D','E'],\
        labeldistance=1.1,pctdistance=0.5,radius=1)
# labeldistance: 控制labels顯示的位置
# pctdistance: 控制百分比顯示的位置
# radius: 控制圓半徑,會和figsize沖突
plt.legend(fontsize=15)
image.png
  • 散點圖
tips = sns.load_dataset("tips")
plt.figure(figsize=(15,6))
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)

plt.sca(ax1)
sns.scatterplot(x="total_bill", y="tip", size='size',hue='time', data=tips)
plt.legend(loc='upper right')

plt.sca(ax2)
sns.stripplot(x="day", y="total_bill",hue='smoker',order=['Sat','Fri','Sun', 'Thur'], jitter=True, dodge=True, data=tips)
plt.legend(loc='upper right')

# order:用order參數(shù)進行篩選分類類別,例如:order=[‘sun’,‘sat’];
# jitter:抖動項,表示抖動程度,可以使float,或者True;
# dodge:重疊區(qū)域是否分開,當使用hue時,將其設置為True,將沿著分類軸將不同色調(diào)級別的條帶分開。
# orient:“v” | “h”,vertical(垂直) 和 horizontal(水平)的意思;
image.png
  • 箱線圖/小提琴圖
tips = sns.load_dataset("tips")
plt.figure(figsize=(15,6))
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)

plt.sca(ax1)
sns.boxplot(x="day", y="total_bill", hue="time",data=tips,)
#箱型圖是四分位點

plt.sca(ax2)
sns.violinplot(x="day", y="total_bill", hue="sex",data=tips)
image.png
  • 直方圖
plt.figure(figsize=(10,6))

np.random.seed(666)
x = np.random.randn(1000)
ax = sns.distplot(x,bins=20,hist=True,kde=True)
image.png
  • 回歸圖
plt.figure(figsize=(10,6))

sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, legend_out=False, height=6,)
plt.legend(loc='upper right')
#回歸圖無法調(diào)整圖片大小,只能用height來設置參數(shù)
image.png
  • 熱力圖
plt.figure(figsize=(10,6))

x= np.random.rand(10, 10)
ax = sns.heatmap(x,annot=True,annot_kws={'size':9, 'color':'black'},fmt='.4f',)
image.png
  • 組合圖

x = np.linspace(0,10)
y = np.linspace(0,10)
z = np.sin(x/3)**2*98

sns.set(style='ticks')
plt.figure(figsize=(10,6))
ax1 = plt.gca()
ax1.plot(x,y, '-', label = 'Quantity 1')

ax2 = ax1.twinx()
ax2.plot(x,z, '-r', label = 'Quantity 2')

ax1.set_xlabel("x [units]")
ax1.set_ylabel(r"Quantity 1")
ax2.set_ylabel(r"Quantity 2")

#圖例
handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
plt.legend(handles1+handles2, labels1+labels2, loc='upper right')
image.png
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容