日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

MatplotlibTutorial——Matplotlib的基本使用【Jupiter Notebook代码】

發(fā)布時間:2024/1/8 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MatplotlibTutorial——Matplotlib的基本使用【Jupiter Notebook代码】 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

加載必要的包

import numpy as np import pandas as pd import matplotlib.pyplot as plt

基本線圖繪圖(學會查文檔)

# 數(shù)據(jù)輸入 x = [0,1,2,3,4] y = [0,1,2,3,4]# 設置圖片大小 plt.figure(figsize=(5,3),dpi=200)# 畫第一個函數(shù) plt.plot(x,y,label='y=x',color='green',marker='^',markersize=10,linewidth=1,linestyle='-') # 加label后面才能顯示legend# 畫第二個分段函數(shù)(有一個預測段) x2 = np.arange(0,4.5,0.5) plt.plot(x2[:3],x2[:3]**2,label='y=x^2',marker='*',color='r') plt.plot(x2[2:],x2[2:]**2,label='y=x^2,prediction',marker='*',color='r',linestyle='--')# 設置標題和坐標軸 plt.title("Our First Graph!",fontdict={'fontsize': 20}) plt.xlabel("X Axis",fontdict={'fontsize':9}) plt.ylabel("Y Axis",fontdict={'fontsize':9})# 設置坐標軸的刻度(或者刻度標簽) #plt.xticks([0,1,1.5,2,3,3.5,4]) #plt.yticks([0,1,2,3,4])# 輸出前設置圖例和網(wǎng)格 plt.legend() plt.grid()# 保存圖片(先保存,后展示) plt.savefig('mygraph.jpg',dpi=700)plt.show()

基本條形圖繪圖

# 輸入數(shù)據(jù) labels = ['A','B','C'] values = [1,4,2]# 基本繪圖 bars = plt.bar(labels,values)# 高階的奇葩設置 #bars[0].set_hatch('/') #bars[1].set_hatch('o') #bars[2].set_hatch('*') patterns = ['/','o','*'] for bar in bars:bar.set_hatch(patterns.pop(0)) # 這種方式更高級了一點# 亂七八糟的設置 plt.title("My Second Graph!",fontdict={'fontsize': 20}) plt.legend()plt.show()

實例教學一:汽油價格

gas = pd.read_csv('./matplotlib_tutorial_download/gas_prices.csv') gas.head() YearAustraliaCanadaFranceGermanyItalyJapanMexicoSouth KoreaUKUSA01234
1990NaN1.873.632.654.593.161.002.052.821.16
19911.961.923.452.904.503.461.302.493.011.14
19921.891.733.563.274.533.581.502.653.061.13
19931.731.573.413.073.684.161.562.882.841.11
19941.841.453.593.523.704.361.482.872.991.11
plt.plot(gas.Year,gas.UK,'r-.') plt.plot(gas.Year,gas.Japan,'b-.')plt.title("Gas Prices Over Time (in USD)")# plt.xticks(range(1990,2009,1),rotation=50) # 這個是一種方法,下面有更好的方法 plt.xticks(gas.Year,rotation=50) # 更好更通用的方法 plt.yticks(range(0,9,1))plt.xlabel("Year") plt.ylabel("Gas Price")plt.grid() plt.legend() plt.show()

plt.plot(gas.Year,gas.UK,'r-.') plt.plot(gas.Year,gas.Japan,'b-.')plt.title("Gas Prices Over Time (in USD)") plt.xticks(gas.Year[::3]) # 每三年來一次進行顯示,顯示效果更好哈哈哈 plt.yticks(range(0,9,1))plt.xlabel("Year") plt.ylabel("Gas Price")plt.grid() plt.legend() plt.show()

# 這里面的邏輯是什么啊??????其實沒有看懂 for country in gas:if country != 'Year':print(country) Australia Canada France Germany Italy Japan Mexico South Korea UK USA # 把上面的語句用于我們的畫圖過程中 # 畫出所有的國家的油價 plt.figure(figsize=(7,5),dpi=500)for country in gas:if country != 'Year':plt.plot(gas.Year,gas[country],marker='.') # 注意這條語句的使用plt.title("Gas Price over Time",fontdict={'fontweight':'bold', 'fontsize':22})plt.xlabel("Year") plt.ylabel("Gas Price")plt.xticks(gas.Year[::3].tolist()+[2011]) plt.yticks(range(0,15,1))plt.legend() plt.savefig('GasPrice.png',dpi=300) plt.show() <matplotlib.figure.Figure at 0x7f0300059780>

實例教學二:FIFA球隊

import numpy as np import pandas as pd import matplotlib.pyplot as plt fifa = pd.read_csv('./matplotlib_tutorial_download/fifa_data.csv') fifa.head() Unnamed: 0IDNameAgePhotoNationalityFlagOverallPotentialClub...ComposureMarkingStandingTackleSlidingTackleGKDivingGKHandlingGKKickingGKPositioningGKReflexesRelease Clause01234
0158023L. Messi31https://cdn.sofifa.org/players/4/19/158023.pngArgentinahttps://cdn.sofifa.org/flags/52.png9494FC Barcelona...96.033.028.026.06.011.015.014.08.0€226.5M
120801Cristiano Ronaldo33https://cdn.sofifa.org/players/4/19/20801.pngPortugalhttps://cdn.sofifa.org/flags/38.png9494Juventus...95.028.031.023.07.011.015.014.011.0€127.1M
2190871Neymar Jr26https://cdn.sofifa.org/players/4/19/190871.pngBrazilhttps://cdn.sofifa.org/flags/54.png9293Paris Saint-Germain...94.027.024.033.09.09.015.015.011.0€228.1M
3193080De Gea27https://cdn.sofifa.org/players/4/19/193080.pngSpainhttps://cdn.sofifa.org/flags/45.png9193Manchester United...68.015.021.013.090.085.087.088.094.0€138.6M
4192985K. De Bruyne27https://cdn.sofifa.org/players/4/19/192985.pngBelgiumhttps://cdn.sofifa.org/flags/7.png9192Manchester City...88.068.058.051.015.013.05.010.013.0€196.4M

5 rows × 89 columns

畫直方圖

bins = np.arange(40,110,10)#plt.hist(fifa.Overall,bins=bins,color='#A87632') # 這里的顏色可以在瀏覽器搜索顏色選擇器進行選擇,然后copy HEX code就好了 plt.hist(fifa.Overall,bins=bins,color='#000000') # 黑色plt.xticks(bins) plt.yticks(np.arange(0,11000,1000))plt.xlabel("Skill levels") plt.ylabel("Number of Players")plt.title("Distribution of Player Skills in FIFA 2018")plt.show()

餅圖 I

fifa['Preferred Foot'] 0 Left 1 Right 2 Right 3 Right 4 Right 5 Right 6 Right 7 Right 8 Right 9 Right 10 Right 11 Right 12 Right 13 Left 14 Right 15 Left 16 Right 17 Left 18 Right 19 Left 20 Right 21 Right 22 Right 23 Right 24 Left 25 Right 26 Left 27 Right 28 Left 29 Right... 18177 Right 18178 Right 18179 Right 18180 Right 18181 Right 18182 Right 18183 Right 18184 Right 18185 Right 18186 Right 18187 Right 18188 Right 18189 Right 18190 Right 18191 Left 18192 Right 18193 Right 18194 Right 18195 Right 18196 Right 18197 Right 18198 Right 18199 Right 18200 Left 18201 Left 18202 Right 18203 Right 18204 Right 18205 Right 18206 Right Name: Preferred Foot, Length: 18207, dtype: object left = fifa.loc[fifa['Preferred Foot']=='Left'].count()[0] print(left) right = fifa.loc[fifa['Preferred Foot']=='Right'].count()[0] print(right) 4211 13948 labels = ['Left','Right'] colors = ['#abcdef','#aabbcc'] plt.pie([left,right],labels=labels,colors=colors,autopct='%.2f %%') # 注意這里面是個方括號plt.title("Foot Preference of FIFA players")plt.show()

餅圖II

fifa.Weight.head() 0 159.0 1 183.0 2 150.0 3 168.0 4 154.0 Name: Weight, dtype: float64 # 去掉這個磅的符號,并且變成一個浮點數(shù) fifa.Weight = [int(x.strip('lbs')) if type(x)==str else x for x in fifa.Weight] fifa.Weight[0] 159.0 light = fifa.loc[fifa.Weight<125].count()[0] print(light) light_medium = fifa.loc[(fifa.Weight>=125) & (fifa.Weight<150)].count()[0] print(light_medium) medium = fifa.loc[(fifa.Weight>=150) & (fifa.Weight<175)].count()[0] print(medium) medium_heavy = fifa.loc[(fifa.Weight>=175) & (fifa.Weight<200)].count()[0] print(medium_heavy) heavy = fifa.loc[fifa.Weight>=200].count()[0] print(heavy)plt.figure(figsize=(5,5),dpi=100)#plt.style.use('default') plt.style.use('ggplot') # 直接用其他的一些風格weights = [light,light_medium,medium,heavy,medium_heavy] labels = ['light','light_medium','medium','heavy','medium_heavy']explode = [.4,.1,.1,.4,.1] # 讓兩個少的往外一點點plt.title("Weight Distrubution of FIFA Players (in lbs)")plt.pie(weights,labels=labels,autopct="%.2f %%",explode=explode)plt.show() 41 2290 10876 4583 369

畫箱形圖

fifa.head() Unnamed: 0IDNameAgePhotoNationalityFlagOverallPotentialClub...ComposureMarkingStandingTackleSlidingTackleGKDivingGKHandlingGKKickingGKPositioningGKReflexesRelease Clause01234
0158023L. Messi31https://cdn.sofifa.org/players/4/19/158023.pngArgentinahttps://cdn.sofifa.org/flags/52.png9494FC Barcelona...96.033.028.026.06.011.015.014.08.0€226.5M
120801Cristiano Ronaldo33https://cdn.sofifa.org/players/4/19/20801.pngPortugalhttps://cdn.sofifa.org/flags/38.png9494Juventus...95.028.031.023.07.011.015.014.011.0€127.1M
2190871Neymar Jr26https://cdn.sofifa.org/players/4/19/190871.pngBrazilhttps://cdn.sofifa.org/flags/54.png9293Paris Saint-Germain...94.027.024.033.09.09.015.015.011.0€228.1M
3193080De Gea27https://cdn.sofifa.org/players/4/19/193080.pngSpainhttps://cdn.sofifa.org/flags/45.png9193Manchester United...68.015.021.013.090.085.087.088.094.0€138.6M
4192985K. De Bruyne27https://cdn.sofifa.org/players/4/19/192985.pngBelgiumhttps://cdn.sofifa.org/flags/7.png9192Manchester City...88.068.058.051.015.013.05.010.013.0€196.4M

5 rows × 89 columns

barcelona = fifa.loc[fifa.Club=='FC Barcelona']['Overall'] madrid = fifa.loc[fifa.Club=='Real Madrid']['Overall'] revs = fifa.loc[fifa.Club=='New England Revolution']['Overall']labels = ['FC Barcelona','Real Madrid','New England Revolution']plt.style.use('default')plt.figure(figsize=(7,10))boxes = plt.boxplot([barcelona, madrid, revs],labels=labels, patch_artist=True) #設置這個True的原因是后面要設置facecolor for box in boxes['boxes']: # 方括號內(nèi)的是參數(shù)# 設置box邊界的顏色box.set(color='#4286f4',linewidth=2)# 設置box內(nèi)部顏色box.set(facecolor='#e0e0e0')plt.title("Professional Soccer Team Comparison") plt.ylabel("FIFA Overall Rating")plt.show() /home/chen/anaconda3/lib/python3.6/site-packages/numpy/core/fromnumeric.py:57: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) insteadreturn getattr(obj, method)(*args, **kwds)

總結

以上是生活随笔為你收集整理的MatplotlibTutorial——Matplotlib的基本使用【Jupiter Notebook代码】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。