python畫折線圖詳解(Python畫折線圖)

前言

這幾天在搞論文圖,唉說實話摳圖這種東西真能逼死人。坐在電腦前摳上一天越看越醜,最後把自己丑哭了……
   到了畫折線圖分析的時候,在想用哪些工具的時候。首先否決了excel,讀書人的事,怎麼能用excel畫論文的圖呢?

然後我又嘗試了Gnuplot、Matlab、Python等。這些軟體作圖無疑是一個非常好的選擇,他們都有一個共同的特點,就是圖片都是用程式碼生成的。
   但是學習成本太高啦。為了畫一個破圖,折騰上十天半個月,誰受得了。
   像小編這種偶爾寫寫程式碼日常懂點程式碼的還好。但那些平時不寫程式碼而且沒有程式碼基礎又沒有一個會寫程式碼的男朋友或者只有一個不會寫程式碼的男朋友的女生可咋辦?

python Matplotlib

最後挑來挑去,最終選用了python Matplotlib。Matplotlib是著名Python的標配畫圖包,其繪圖函式的名字基本上與 Matlab 的繪圖函式差不多。優點是曲線精緻,軟體開源免費,支援Latex公式插入,且許多時候只需要一行或幾行程式碼就能搞定。
   然後小編經過了幾天的摸索,找了幾個不錯的python程式碼模板,供大家簡單修改就能快速上手使用。建議使用Wing Personal 作為PythonIDE,生成的圖片能上下左右進行調整:

NO.1

# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['Arial']#如果要顯示中文字型,則在此處設為:SimHei plt.rcParams['axes.unicode_minus']=False#顯示負號 x = np.array([3,5,7,9,11,13,15,17,19,21]) A = np.array([0.9708, 0.6429, 1, 0.8333, 0.8841, 0.5867, 0.9352, 0.8000, 0.9359, 0.9405]) B= np.array([0.9708, 0.6558, 1, 0.8095, 0.8913, 0.5950, 0.9352, 0.8000, 0.9359, 0.9419]) C=np.array([0.9657, 0.6688, 0.9855, 0.7881, 0.8667, 0.5952, 0.9361, 0.7848, 0.9244, 0.9221]) D=np.array([0.9664, 0.6701, 0.9884, 0.7929, 0.8790, 0.6072, 0.9352, 0.7920, 0.9170, 0.9254]) #label在圖示(legend)中顯示。若為數學公式,則最好在字串前後新增"$"符號 #color:b:blue、g:green、r:red、c:cyan、m:magenta、y:yellow、k:black、w:white、、、 #線型:-  --   -.  :    , #marker:.  ,   o   v    <    *         1 plt.figure(figsize=(10,5)) plt.grid(linestyle = "--") #設定背景網格線為虛線 ax = plt.gca() ax.spines['top'].set_visible(False) #去掉上邊框 ax.spines['right'].set_visible(False) #去掉右邊框 plt.plot(x,A,color="black",label="A algorithm",linewidth=1.5) plt.plot(x,B,"k--",label="B algorithm",linewidth=1.5) plt.plot(x,C,color="red",label="C algorithm",linewidth=1.5) plt.plot(x,D,"r--",label="D algorithm",linewidth=1.5) group_labels=['dataset1','dataset2','dataset3','dataset4','dataset5',' dataset6','dataset7','dataset8','dataset9','dataset10'] #x軸刻度的標識 plt.xticks(x,group_labels,fontsize=12,fontweight='bold') #預設字型大小為10 plt.yticks(fontsize=12,fontweight='bold') plt.title("example",fontsize=12,fontweight='bold') #預設字型大小為12 plt.xlabel("Data sets",fontsize=13,fontweight='bold') plt.ylabel("Accuracy",fontsize=13,fontweight='bold') plt.xlim(3,21) #設定x軸的範圍 #plt.ylim(0.5,1) #plt.legend()          #顯示各曲線的圖例 plt.legend(loc=0, numpoints=1) leg = plt.gca().get_legend() ltext = leg.get_texts() plt.setp(ltext, fontsize=12,fontweight='bold') #設定圖例字型的大小和粗細 plt.savefig('D://filename.png') #建議儲存為svg格式,再用inkscape轉為向量圖emf後插入word中 plt.show()

效果圖:

NO.2

# coding=utf-8 import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Arial']  # 如果要顯示中文字型,則在此處設為:SimHei plt.rcParams['axes.unicode_minus'] = False  # 顯示負號 x = np.array([1, 2, 3, 4, 5, 6]) VGG_supervised = np.array([2.9749694, 3.9357018, 4.7440844, 6.482254, 8.720203, 13.687582]) VGG_unsupervised = np.array([2.1044724, 2.9757383, 3.7754183, 5.686206, 8.367847, 14.144531]) ourNetwork = np.array([2.0205495, 2.6509762, 3.1876223, 4.380781, 6.004548, 9.9298]) # label在圖示(legend)中顯示。若為數學公式,則最好在字串前後新增"$"符號 # color:b:blue、g:green、r:red、c:cyan、m:magenta、y:yellow、k:black、w:white、、、 # 線型:-  --   -.  :    , # marker:.  ,   o   v    <    *         1 plt.figure(figsize=(10, 5)) plt.grid(linestyle="--")  # 設定背景網格線為虛線 ax = plt.gca() ax.spines['top'].set_visible(False)  # 去掉上邊框 ax.spines['right'].set_visible(False)  # 去掉右邊框 plt.plot(x, VGG_supervised, marker='o', color="blue", label="VGG-style Supervised Network", linewidth=1.5) plt.plot(x, VGG_unsupervised, marker='o', color="green", label="VGG-style Unsupervised Network", linewidth=1.5) plt.plot(x, ourNetwork, marker='o', color="red", label="ShuffleNet-style Network", linewidth=1.5) group_labels = ['Top 0-5%', 'Top 5-10%', 'Top 10-20%', 'Top 20-50%', 'Top 50-70%', ' Top 70-100%']  # x軸刻度的標識 plt.xticks(x, group_labels, fontsize=12, fontweight='bold')  # 預設字型大小為10 plt.yticks(fontsize=12, fontweight='bold') # plt.title("example", fontsize=12, fontweight='bold')  # 預設字型大小為12 plt.xlabel("Performance Percentile", fontsize=13, fontweight='bold') plt.ylabel("4pt-Homography RMSE", fontsize=13, fontweight='bold') plt.xlim(0.9, 6.1)  # 設定x軸的範圍 plt.ylim(1.5, 16) # plt.legend()          #顯示各曲線的圖例 plt.legend(loc=0, numpoints=1) leg = plt.gca().get_legend() ltext = leg.get_texts() plt.setp(ltext, fontsize=12, fontweight='bold')  # 設定圖例字型的大小和粗細 plt.savefig('./filename.svg', format='svg')  # 建議儲存為svg格式,再用inkscape轉為向量圖emf後插入word中 plt.show()

效果圖:

NO.3

# coding=utf-8 import matplotlib.pyplot as plt from matplotlib.pyplot import figure import numpy as np figure(num=None, figsize=(2.8, 1.7), dpi=300) #figsize的2.8和1.7指的是英寸,dpi指定圖片解析度。那麼圖片就是(2.8*300)*(1.7*300)畫素大小 test_mean_1000S_n = [0.7,0.5,0.3,0.8,0.7,0.5,0.3,0.8,0.7,0.5,0.3,0.8,0.7,0.5,0.3,0.8,0.7,0.5,0.3,0.8] test_mean_1000S   = [0.9,0.8,0.7,0.6,0.9,0.8,0.7,0.6,0.9,0.8,0.7,0.6,0.9,0.8,0.7,0.6,0.9,0.8,0.7,0.6] plt.plot(test_mean_1000S_n, 'royalblue', label='without threshold') plt.plot(test_mean_1000S, 'darkorange', label='with threshold') #畫圖,並指定顏色 plt.xticks(fontproperties = 'Times New Roman', fontsize=8) plt.yticks(np.arange(0, 1.1, 0.2), fontproperties = 'Times New Roman', fontsize=8) #指定橫縱座標的字型以及字型大小,記住是fontsize不是size。yticks上我還用numpy指定了座標軸的變化範圍。 plt.legend(loc='lower right', prop={'family':'Times New Roman', 'size':8}) #圖上的legend,記住字型是要用prop以字典形式設定的,而且字的大小是size不是fontsize,這個容易和xticks的命令弄混 plt.title('1000 samples', fontdict={'family' : 'Times New Roman', 'size':8}) #指定圖上標題的字型及大小 plt.xlabel('iterations', fontdict={'family' : 'Times New Roman', 'size':8}) plt.ylabel('accuracy', fontdict={'family' : 'Times New Roman', 'size':8}) #指定橫縱座標描述的字型及大小 plt.savefig('./where-you-want-to-save.png', dpi=300, bbox_inches="tight") #儲存檔案,dpi指定儲存檔案的解析度 #bbox_inches="tight" 可以儲存圖上所有的資訊,不會出現橫縱座標軸的描述存掉了的情況 plt.show() #記住,如果你要show()的話,一定要先savefig,再show。如果你先show了,存出來的就是一張白紙。

效果圖:

最後在放點Matplotlib相關設定供大家參考:

附顏色表

Marker常見引數

注:大家可以mark一下,說不定以後用得上呢?

最後,我還是用回了excel作圖。。。