Matplotlib 库是 python 的数据可视化库
import matplotlib.pyplot as plt

1、字符串转化为日期

unrate = pd.read_csv("unrate.csv")
unrate["DATE"] = pd.to_datetime(unrate["DATE"])

2、拆线图

data1 = unrate[0: 12]
plt.plot(data1["DATE"], data1["VALUE"]) # x轴数据和y轴数据
plt.xticks(rotation = 45) # 将x轴的属性旋转一个角度
plt.xlabel("Date Month") # x轴描述
plt.ylabel("Rate Value") # y轴描述
plt.title("my first plt") # 标题
plt.show()

3、多图拼切

fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)
ax1.plot(np.random.randint(1, 5, 5), np.arange(5))
ax2.plot(np.arange(10)*3, np.arange(10))
plt.show()

4、一图多线

fig = plt.figure(figsize=(6, 3)) # 设定图尺寸

data1 = unrate[0: 12]
data1["MONTH"] = data1["DATE"].dt.month
plt.plot(data1["MONTH"], data1["VALUE"], c="red") data2 = unrate[12: 24]
data2["MONTH"] = data2["DATE"].dt.month
plt.plot(data2["MONTH"], data2["VALUE"], c="blue") plt.xticks(rotation = 45) #将x轴的属性旋转一个角度
plt.xlabel("Date Month")
plt.ylabel("Rate Value")
plt.title("my first plt")
plt.show()

5、一图多线 - 自动跑代码(带图例)

fig = plt.figure(figsize=(10, 6))

colors = ['red', 'blue', 'green', 'orange', 'black']
for i in range(5):
start_index = i*12
end_index = (i+1)*12
subset = unrate[start_index: end_index] label = str(1948 + i)
plt.plot(subset['MONTH'], subset['VALUE'], c=colors[i], label=label) # plt.legend(loc='best')
plt.legend(loc = 'upper left') # 位置
plt.show()

6、条形图

fand_col = ["Fandango_Stars", "Fandango_Ratingvalue", "Metacritic_norm", "RT_user_norm_round", "IMDB_norm_round"]

bar_heights = fand_new.ix[0, fand_col].values # 条形图高度
bar_positions = np.arange(5) + 0.75 # 条形图起始位置
tick_positions = range(1, 6)
fig, ax = plt.subplots() ax.bar(bar_positions, bar_heights, 0.5) # 0.5表示条形图的宽度
ax.set_xticks(tick_positions)
ax.set_xticklabels(fand_col, rotation = 90) ax.set_xlabel('Rating Source')
ax.set_ylabel('Average Rating')
ax.set_title('Average User Rating For Avengers: Age of Ultron (2015)')
plt.show()

7、条形图 - 横向

fand_col = ["Fandango_Stars", "Fandango_Ratingvalue", "Metacritic_norm", "RT_user_norm_round", "IMDB_norm_round"]
bar_heights = fand_new.ix[0, fand_col].values
bar_positions = np.arange(5) + 0.75
tick_positions = range(1, 6)
fig, ax = plt.subplots() ax.barh(bar_positions, bar_heights, 0.5) # 横向
ax.set_yticks(tick_positions)
ax.set_yticklabels(fand_col, rotation = 0) ax.set_xlabel('Rating Source')
ax.set_ylabel('Average Rating')
ax.set_title('Average User Rating For Avengers: Age of Ultron (2015)')
plt.show()

8、散点图

fig, ax = plt.subplots()
ax.scatter(fand_new['Fandango_Stars'], fand_new['Metacritic_norm']) # 散点图
ax.set_xlabel('Fandango')
ax.set_ylabel('Rotten Tomatoes')
plt.show()

9、直方图

fandango_distribution = fand_new['Fandango_Stars'].value_counts()
fandango_distribution = fandango_distribution.sort_index()
imdb_distribution = fand_new['IMDB_norm_round'].value_counts()
imdb_distribution = imdb_distribution.sort_index() # bins 是什么?通俗一点就是分组,将N多数据分成X组。默认:bins=10
fig, ax = plt.subplots()
ax.hist(fand_new['Fandango_Stars'], range=(4, 5), bins=5) # range 需要查看x轴的范围
plt.show()

10、多图

fig = plt.figure(figsize=(12, 12))
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
ax1.hist(fand_new['Fandango_Stars'], bins=20, range=(0, 5))
ax1.set_title('Distribution of Fandango Ratings')
ax1.set_ylim(0, 50) ax2.hist(fand_new['IMDB_norm_round'], 20, range=(0, 5))
ax2.set_title('Distribution of Rotten Tomatoes Ratings')
ax2.set_ylim(0, 50) ax3.hist(fand_new['Metacritic_norm'], 20, range=(0, 5))
ax3.set_title('Distribution of Metacritic Ratings')
ax3.set_ylim(0, 50) ax4.hist(fand_new['RT_user_norm_round'], 20, range=(0, 5))
ax4.set_title('Distribution of IMDB Ratings')
ax4.set_ylim(0, 50) plt.show()

11、四分图

fig, ax = plt.subplots()

ax.boxplot(fand_new['Metacritic_norm'])
ax.set_xticklabels(['Rotten Tomatoes'])
ax.set_ylim(0, 5) plt.show()

12、多图 - 通过数组

num_cols = ['Fandango_Stars', 'IMDB_norm_round', 'Metacritic_norm', 'RT_user_norm_round']
fig, ax = plt.subplots() ax.boxplot(fand_new[num_cols].values)
ax.set_xticklabels(num_cols, rotation=90)
ax.set_ylim(0, 5) plt.show()

13、数据可视化 - 简洁一些

fig, ax = plt.subplots()

ax.plot(women_degrees['Year'], women_degrees['Biology'], c='blue', label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees['Biology'], c='green', label='Men')
ax.tick_params(bottom="off", top="off", left="off", right="off") # 可配置参数 for key,spine in ax.spines.items():
spine.set_visible(False) ax.legend(loc='upper right') plt.show()

14、数据可视化 - 多图 - 通过程序

major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']

fig = plt.figure(figsize=(12, 12))

for sp in range(0, 4):
ax = fig.add_subplot(2, 2, sp+1)
ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c='blue', label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c='green', label='Men') plt.legend(loc='upper right')
plt.show()

15、数据可视化 - 多图 - 通过程序跑 - 多图 简洁

major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']

fig = plt.figure(figsize=(12, 12))

for sp in range(0, 4):
ax = fig.add_subplot(2, 2, sp+1)
ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c='blue', label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c='green', label='Men') for key,spine in ax.spines.items():
spine.set_visible(False) ax.set_xlim(1968, 2011)
ax.set_ylim(0,100)
ax.set_title(major_cats[sp])
ax.tick_params(bottom="off", top="off", left="off", right="off") plt.legend(loc='upper right')
plt.show()

16、如何使图表更好看?

cb_dark_blue = (0/255, 107/255, 164/255)    # 自定义颜色
cb_orange = (255/255, 128/255, 14/255) fig = plt.figure(figsize=(12, 12)) for sp in range(0, 4):
ax = fig.add_subplot(2, 2, sp+1)
ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c=cb_dark_blue, label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c=cb_orange, label='Men') for key,spine in ax.spines.items():
spine.set_visible(False) ax.set_xlim(1968, 2011)
ax.set_ylim(0,100)
ax.set_title(major_cats[sp])
ax.tick_params(bottom="off", top="off", left="off", right="off") plt.legend(loc='upper right')
plt.show()

17、加粗线

cb_dark_blue = (0/255, 107/255, 164/255)
cb_orange = (255/255, 128/255, 14/255) fig = plt.figure(figsize=(18, 3)) for sp in range(0, 4):
ax = fig.add_subplot(1, 4, sp+1)
ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c=cb_dark_blue, label='Women', linewidth=3) # 线条粗细
ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c=cb_orange, label='Men', linewidth=3) for key,spine in ax.spines.items():
spine.set_visible(False) ax.set_xlim(1968, 2011)
ax.set_ylim(0,100)
ax.set_title(major_cats[sp])
ax.tick_params(bottom="off", top="off", left="off", right="off") plt.legend(loc='upper right')
plt.show()

18、加注释

fig = plt.figure(figsize=(18, 3))

for sp in range(0, 4):
ax = fig.add_subplot(1, 4, sp+1)
ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c=cb_dark_blue, label='Women', linewidth=3)
ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c=cb_orange, label='Men', linewidth=3)
for key,spine in ax.spines.items():
spine.set_visible(False)
ax.set_xlim(1968, 2011)
ax.set_ylim(0,100)
ax.set_title(major_cats[sp])
ax.tick_params(bottom="off", top="off", left="off", right="off") if sp == 0:
ax.text(2005, 87, 'Men') # 注释
ax.text(2002, 8, 'Women')
elif sp == 3:
ax.text(2005, 62, 'Men')
ax.text(2001, 35, 'Women') plt.show()

Python的Matplotlib库简述的更多相关文章

  1. Python之matplotlib库学习:实现数据可视化

    1. 安装和文档 pip install matplotlib 官方文档 为了方便显示图像,还使用了ipython qtconsole方便显示.具体怎么弄网上搜一下就很多教程了. pyplot模块是提 ...

  2. Python基础——matplotlib库的使用与绘图可视化

    1.matplotlib库简介: Matplotlib 是一个 Python 的 2D绘图库,开发者可以便捷地生成绘图,直方图,功率谱,条形图,散点图等. 2.Matplotlib 库使用: 注:由于 ...

  3. Python之matplotlib库学习

    matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图.而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中. 它的文档相当完备, ...

  4. Python的Pandas库简述

    pandas 是 python 的数据分析处理库import pandas as pd 1.读取CSV.TXT文件 foodinfo = pd.read_csv("pandas_study. ...

  5. Python的Numpy库简述

    numpy 是 python 的科学计算库import numpy as np 1.使用numpy读取txt文件 # dtype = "str":指定数据格式 # delimite ...

  6. Python的matplotlib库画图不能显示中文问题解决

    有两种解决办法: 一种是在代码里设置为能显示中文的字体,如微软雅黑(msyh.ttf)和黑体(simsun.ttc) 如下在要画图的代码前添加: import matplotlib.pyplot as ...

  7. Python之Matplotlib库常用函数大全(含注释)

    plt.savefig(‘test’, dpi = 600) :将绘制的图画保存成png格式,命名为 test plt.ylabel(‘Grade’) :  y轴的名称 plt.axis([-1, 1 ...

  8. Python之matplotlib库

    知识结构 pyplot.plot()流程 1. _axes.py中plot()函数说明 a. 调用说明 plot([x], y, [fmt], data=None, **kwargs)       p ...

  9. python 利用matplotlib中imshow()函数绘图

    matplotlib 是python最著名的2D绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图.而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中.通过简单的绘图语 ...

随机推荐

  1. [实战]MVC5+EF6+MySql企业网盘实战(4)——上传头像

    写在前面 最近又开始忙了,工期紧比较赶,另外明天又要去驾校,只能一个功能一个功能的添加了,也许每次完成的功能确实不算什么,等将功能都实现了,然后在找一个好点的ui对前端重构一下. 系列文章 [EF]v ...

  2. Warning: Failed to halt at after bootloader, forced stop at

    该错误证实是因为 cc2650 SW下载模式,芯片复位引脚未接出来导致,芯片复位必须和下载器保持良好连接

  3. python--json串相关的loads dumps load dump

    #1 json串长的像字典,但不是字典类型,是str类型 #例如:user_info为json串,dict为字典,如果txt文本中标识dict的内容 为json串user_info = '''{&qu ...

  4. [daily][tcpdump][bpf] 如何用tcpdump抓到一个分片包

    tcpdump -r web_185.pcap "ip[6:2] & 0x1fff != 0" tcpdump -r web_185.pcap "ip[6:2] ...

  5. dp进阶——饥饿的奶牛

    饥饿的奶牛oj上n只有1000,过于水,O(n^2)的算法很容易水过,洛谷上这是一道提高加的题,很难啊,所以要好好拿来练习今天写博客再次复习一下,oi最怕遗忘了. 这道题呢实质是一个区间覆盖的dp,首 ...

  6. odoo权限管理

    Odoo的权限的核心是权限组(res_groups).对每个权限组,可以设置权限组的菜单表示,对象表示,记录规则表示,字段表示. 1.菜单/对象级别 设置哪些人可以访问哪些菜单/对象,对象的访问权限包 ...

  7. 转:ActiveMQ的作用总结(应用场景及优势)

    原文地址: ActiveMQ的作用总结(应用场景及优势) 业务场景说明: 消息队列在大型电子商务类网站,如京东.淘宝.去哪儿等网站有着深入的应用, 队列的主要作用是消除高并发访问高峰,加快网站的响应速 ...

  8. 图->存储结构->邻接多重表

    文字描述 邻接多重表是无向图的另一种链式存储结构. 虽然邻接表是无向图的一种很有效的存储结构,在邻接表中容易求得顶点和边的各种信息. 但是,在邻接表中每一条边(vi,vj)有两个结点,分别在第i个和第 ...

  9. elasticsearch解决控制台中文乱码问题

    找到conf目录下的jvm.options文件,找到如下的配置行: 我将之前的UTF-8 改成GBK,ok.

  10. 20165336 2016-2017-2 《Java程序设计》第9周学习总结

    20165336 2016-2017-2 <Java程序设计>第9周学习总结 教材学习内容总结 1.URL类:URL类是java.net包中的一个重要的类,使用URL创建对象的应用程序称作 ...