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

加载必要的包

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

基本线图绘图(学会查文档)

# 数据输入
x = [0,1,2,3,4]
y = [0,1,2,3,4]

# 设置图片大小
plt.figure(figsize=(5,3),dpi=200)

# 画第一个函数
plt.plot(x,y,label='y=x',color='green',marker='^',markersize=10,linewidth=1,linestyle='-')  # 加label后面才能显示legend

# 画第二个分段函数(有一个预测段)
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])

# 输出前设置图例和网格
plt.legend()
plt.grid()

# 保存图片(先保存,后展示)
plt.savefig('mygraph.jpg',dpi=700)

plt.show()

在这里插入图片描述

基本条形图绘图

# 输入数据
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 KoreaUKUSA
01990NaN1.873.632.654.593.161.002.052.821.16
119911.961.923.452.904.503.461.302.493.011.14
219921.891.733.563.274.533.581.502.653.061.13
319931.731.573.413.073.684.161.562.882.841.11
419941.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 Clause
00158023L. 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
1120801Cristiano 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
22190871Neymar 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
33193080De 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
44192985K. 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
# 去掉这个磅的符号,并且变成一个浮点数
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 Clause
00158023L. 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
1120801Cristiano 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
22190871Neymar 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
33193080De 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
44192985K. 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']:  # 方括号内的是参数
    # 设置box边界的颜色
    box.set(color='#4286f4',linewidth=2)
    # 设置box内部颜色
    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(...) instead
  return getattr(obj, method)(*args, **kwds)

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值