加载必要的包

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()
Year Australia Canada France Germany Italy Japan Mexico South Korea UK USA
0 1990 NaN 1.87 3.63 2.65 4.59 3.16 1.00 2.05 2.82 1.16
1 1991 1.96 1.92 3.45 2.90 4.50 3.46 1.30 2.49 3.01 1.14
2 1992 1.89 1.73 3.56 3.27 4.53 3.58 1.50 2.65 3.06 1.13
3 1993 1.73 1.57 3.41 3.07 3.68 4.16 1.56 2.88 2.84 1.11
4 1994 1.84 1.45 3.59 3.52 3.70 4.36 1.48 2.87 2.99 1.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: 0 ID Name Age Photo Nationality Flag Overall Potential Club ... Composure Marking StandingTackle SlidingTackle GKDiving GKHandling GKKicking GKPositioning GKReflexes Release Clause
0 0 158023 L. Messi 31 https://cdn.sofifa.org/players/4/19/158023.png Argentina https://cdn.sofifa.org/flags/52.png 94 94 FC Barcelona ... 96.0 33.0 28.0 26.0 6.0 11.0 15.0 14.0 8.0 €226.5M
1 1 20801 Cristiano Ronaldo 33 https://cdn.sofifa.org/players/4/19/20801.png Portugal https://cdn.sofifa.org/flags/38.png 94 94 Juventus ... 95.0 28.0 31.0 23.0 7.0 11.0 15.0 14.0 11.0 €127.1M
2 2 190871 Neymar Jr 26 https://cdn.sofifa.org/players/4/19/190871.png Brazil https://cdn.sofifa.org/flags/54.png 92 93 Paris Saint-Germain ... 94.0 27.0 24.0 33.0 9.0 9.0 15.0 15.0 11.0 €228.1M
3 3 193080 De Gea 27 https://cdn.sofifa.org/players/4/19/193080.png Spain https://cdn.sofifa.org/flags/45.png 91 93 Manchester United ... 68.0 15.0 21.0 13.0 90.0 85.0 87.0 88.0 94.0 €138.6M
4 4 192985 K. De Bruyne 27 https://cdn.sofifa.org/players/4/19/192985.png Belgium https://cdn.sofifa.org/flags/7.png 91 92 Manchester City ... 88.0 68.0 58.0 51.0 15.0 13.0 5.0 10.0 13.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: 0 ID Name Age Photo Nationality Flag Overall Potential Club ... Composure Marking StandingTackle SlidingTackle GKDiving GKHandling GKKicking GKPositioning GKReflexes Release Clause
0 0 158023 L. Messi 31 https://cdn.sofifa.org/players/4/19/158023.png Argentina https://cdn.sofifa.org/flags/52.png 94 94 FC Barcelona ... 96.0 33.0 28.0 26.0 6.0 11.0 15.0 14.0 8.0 €226.5M
1 1 20801 Cristiano Ronaldo 33 https://cdn.sofifa.org/players/4/19/20801.png Portugal https://cdn.sofifa.org/flags/38.png 94 94 Juventus ... 95.0 28.0 31.0 23.0 7.0 11.0 15.0 14.0 11.0 €127.1M
2 2 190871 Neymar Jr 26 https://cdn.sofifa.org/players/4/19/190871.png Brazil https://cdn.sofifa.org/flags/54.png 92 93 Paris Saint-Germain ... 94.0 27.0 24.0 33.0 9.0 9.0 15.0 15.0 11.0 €228.1M
3 3 193080 De Gea 27 https://cdn.sofifa.org/players/4/19/193080.png Spain https://cdn.sofifa.org/flags/45.png 91 93 Manchester United ... 68.0 15.0 21.0 13.0 90.0 85.0 87.0 88.0 94.0 €138.6M
4 4 192985 K. De Bruyne 27 https://cdn.sofifa.org/players/4/19/192985.png Belgium https://cdn.sofifa.org/flags/7.png 91 92 Manchester City ... 88.0 68.0 58.0 51.0 15.0 13.0 5.0 10.0 13.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(...) insteadreturn getattr(obj, method)(*args, **kwds)

MatplotlibTutorial——Matplotlib的基本使用【Jupiter Notebook代码】相关推荐

  1. 使用 Jupiter Notebook 运行 Delta Lake 入门教程

    作者:吴威,花名无谓,阿里巴巴高级技术专家,2008年加入阿里巴巴集团,先后在B2B和阿里云工作,一直从事大数据和分布式计算相关研究,作为主要开发和运维.人员经历了阿里内部大数据集群的上线和发展壮大, ...

  2. Python科学计算学习:从入门到放弃系列(3)工具篇 IPython (Jupiter Notebook) 使用介绍

    1.前言 兵欲善其事,必先利其器. 发现这句话真的好有道理,我是按着张若愚的教材学Python科学计算的,他整本书,对,整本书,均是用IPython写的,也就是,编码演示和书籍撰写两不误.在这之前,我 ...

  3. python 画三维函数图-如何用Matplotlib 画三维图的示例代码

    最基本的三维图是由(x, y, z)三维坐标点构成的线图与散点图,可以用ax.plot3D和ax.scatter3D函数来创建,默认情况下,散点会自动改变透明度,以在平面上呈现出立体感 三维的线图和散 ...

  4. python画三维立体图-如何用Matplotlib 画三维图的示例代码

    用Matplotlib画三维图 最基本的三维图是由(x, y, z)三维坐标点构成的线图与散点图,可以用ax.plot3D和ax.scatter3D函数来创建,默认情况下,散点会自动改变透明度,以在平 ...

  5. python 做界面时如何使图片保持透明背景_Python matplotlib生成图片背景透明的示例代码...

    使用matplotlib生成图片,想要背景透明,而且图例部分也显示透明效果,找到了大概的设置方法,特此记录. # coding=utf-8 # matplotlib背景透明示例图 # python 3 ...

  6. python怎样画立体图-如何用Matplotlib 画三维图的示例代码

    用Matplotlib画三维图 最基本的三维图是由(x, y, z)三维坐标点构成的线图与散点图,可以用ax.plot3D和ax.scatter3D函数来创建,默认情况下,散点会自动改变透明度,以在平 ...

  7. Jupyter Notebook 代码补全功能配置

    Jupyter Notebook 代码补全功能配置 Jupyter Notebook 按Tab键可以实现代码补全,但是没有代码提示,代码提示功能可以通过以下配置实现 1.安装配置包 1.1打开 Ana ...

  8. python画三维立体图完整代码_如何用Matplotlib 画三维图的示例代码

    最基本的三维图是由(x, y, z)三维坐标点构成的线图与散点图,可以用ax.plot3D和ax.scatter3D函数来创建,默认情况下,散点会自动改变透明度,以在平面上呈现出立体感 三维的线图和散 ...

  9. Python代码在Pycharm中不起作用,但在Jupiter Notebook中执行良好

    代码 import requests from apscheduler.schedulers.background import BackgroundScheduler from datetime i ...

最新文章

  1. 学习《Linux设备模型浅析之设备篇》笔记(深挖一)
  2. oracle经典增删该查,oracle基本语法(增删改查
  3. 【数据分析】Databricks入门:分析COVID-19
  4. SQL注入学习——时间盲注详解 sqli-labs(Less 9)
  5. 雷林鹏分享:Ruby Web Services 应用 - SOAP4R
  6. 多任务实现-协程(python 版)
  7. python for else statement test
  8. 通过Chrome浏览器检测和优化页面
  9. 发送ajax的get请求,AJAX之发送GET请求
  10. 内网穿透工具,微信支付支付宝支付的沙箱接口回调地址
  11. linux重启tomcat命令
  12. 渗透测试工具包 | 开源安全测试工具 | 网络安全工具
  13. 如何积累人生的第一桶金
  14. Unity Timeline自定义轨道 DefaultPlayables源码剖析
  15. Java中创建Excel文档,POI使用详解
  16. 揪出手机耗电元凶——高德地图缓存数据
  17. 使用 Levenshtein 寻找彼此相似的字符串对
  18. python编程midi键盘按键错乱_电脑键盘按键错乱怎么回事?几步轻松搞定
  19. pro缺点和不足 一加7t_一加7T Pro深度体验半个月以后:优点和缺点都很明显
  20. [APIO2018] New Home 新家

热门文章

  1. 普歌-Vue 封装防刷新考试倒计时组
  2. php投影,投影+直播双模式方案搭建
  3. 看设计师大牛如何将用户体验与建站融会贯通
  4. PrecompiledAssemblyException: Multiple precompiled assemblies with the same name websocket-sharp.dll
  5. Android手机下载的缓存视频如何找到?
  6. 关于Maven打包Java Web项目以及热部署插件Jrebel的使用
  7. Java imageio底层_java - Java中的ImageIO问题 - 堆栈内存溢出
  8. Scratch教学课程:不撞南墙不回头
  9. EOS区块链技术开发(〇)起源
  10. docker镜像仓库habor1.10.0安装配置-单机版