Matplotlib绘制各种图形

简介

matplotlib是Python的一款2D绘图软件,用它可以较方便的绘制出各种统计图。
下面是matplotlib绘制各种图形的基本用法,更详细的使用方法可以参考官方文档https://matplotlib.org/api/pyplot_summary.html

全局设置:

import numpy as np
from matplotlib import pyplot as plt#导入pyplot绘图工具
%matplotlib inline#在Jupyter notebook中由于每个人的环境有差异,有些必须执行plt.show()才能将图片显示出来,加上这行就不用show()也能显示了
plt.rcParams['font.sans-serif']=["SimHei"]#
plt.rcParams['axes.unicode_minus'] = False#解决中文乱码的问题
条形图

plt.plot()是绘制折线图的方法

#创建画板
plt.figure(figsize=(8,4))  # 8inch*4inch
#绘制折线图plt.plot()
plt.plot([1, 2, 3],[10, 14, 12], label="第一条线")
plt.plot([1, 2, 3], [5, 7, 4], label="第二条线")
#plt.show()  如果在pycharm中,必须要调用show函数显示图表
# plt.xlabel("x轴")
# plt.ylabel("y轴")
plt.legend()#图例
plt.title("123")
# plt.show()

柱状图

plt.bar()

x = np.arange(1, 10, 2)
y = [5, 2, 7, 8, 2]
x1 = np.arange(2, 11, 2)
y1 = [8, 6, 2, 5, 6]
plt.bar(x, y, label="柱状图1")
plt.bar(x1, y1, label="柱状图2", color="r", width=1.1)

条形图

plt.barh()
使用方法同柱状图

直方图
ages = np.random.randint(0, 100, 30)#年纪
bins = np.arange(0, 100, 10)
plt.hist(ages, bins, histtype="barstacked", rwidth=0.8)#年纪频率直方图, rwidth是柱子的宽度

扇形图
players = [10, 20, 3, 90]
plt.figure(figsize=(10, 10))
types = ["wow", "war3", "cs", "lol"]
plt.pie(players, #label
        labels=types, #标签
        startangle=90, #旋转角度
        shadow=True, #阴影
        autopct="%1.1f%%", #百分比显示
        explode=(0, 0.2, 0, 0), #突出显示第1个
        textprops={"fontsize":20})#字体属性,这里设大小为20

散点图
x = np.arange(1, 9)
y = np.random.randint(1, 6, 8)
plt.scatter(x, y, label="x", color="k", s=25, marker="o")

堆叠图
plt.stackplot(days, 
              sleeping,eating,working,playing,
              labels=["Sleeping", "Eating", "Working", "Playing"],
              colors=["r", "g", "m", "y"])
正余弦
#三角函数
plt.figure(figsize=(10, 7))#取出一张10*7的白纸
ax = plt.gca()#
ax.spines["bottom"].set_position(("data", 0))
ax.spines["left"].set_position(("data", 0))
ax.spines["top"].set_color("none")
ax.spines["right"].set_color("none")
ax.xaxis.set_ticks_position("bottom")
X = np.linspace(-np.pi, np.pi, 512, endpoint=True)#在-np.pi~np.pi之间选择256个等差数
S, C = np.sin(X), np.cos(X)
# print(X)
# print(S, C, sep="\n")
plt.plot(X, S, "-", lw=2, aa=False, ms=50, label="sin")#设置线宽5 关闭抗锯齿 默认开启
plt.plot(X, C, "-", lw=2, aa=True, label="cos")#线宽10
plt.xlim(X.min() * 1.2, X.max() * 1.2)#横坐标范围
plt.ylim(S.min() * 1.2, S.max() * 1.2)#纵坐标范围
plt.xticks([0, X.max(), X.min()], [0, r"$\pi$", "$-\pi$"])#横坐标刻度
plt.yticks([S.min(), S.max()])#纵坐标刻度
plt.legend(fontsize=20)
t = 2 / 3 * np.pi
plt.plot([t, t], [0, np.sin(t)], "--", color="b")
plt.scatter([t], [np.sin(t)], s=100)#散点图
#设置标注
plt.annotate(r"$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$",
             (t, np.sin(t)),
             xycoords="data", textcoords="offset pixels",
             xytext=(20, 20),
             arrowprops=dict(arrowstyle="->" , connectionstyle="arc3,rad=.2"),#箭头属性
             fontsize=16,#zi字体大小
            )
plt.plot([t, t], [0, np.cos(t)], "--", color="r")
plt.scatter([t], [np.cos(t)], s=100)#散点图
#设置标注
plt.annotate(r"$\cos(\frac{2\pi}{3})=-\frac{1}{2}$",
             (t, np.cos(t)),
             xycoords="data", textcoords="offset pixels",
             xytext=(20, 0),
             arrowprops=dict(arrowstyle="->" , connectionstyle="arc3,rad=.2"),#箭头属性
             fontsize=16,#zi字体大小
            )

加载本地csv文件并可视化
x, y = np.loadtxt("./matplotlib-demo.csv", delimiter=",", usecols=(0, 1), unpack=True)
print(x, y)
plt.plot(x, y, label="折线图")
plt.title("numpy读取csv文件并用matplotlib可视化")

加载网络图片
response = requests.get("https://api.douban.com/v2/book/1220562")
print(response.text)
js_str = json.loads(response.text)
tags = js_str["tags"]
x = []
y = []
for tag in tags:
    x.append(tag["name"])
    y.append(tag["count"])
plt.bar(x, y, label="图书热门标签")
plt.legend()
plt.xlabel("搜索标签")
plt.ylabel("搜索标签排名")
plt.title("图书热词搜索排名")

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辣椒种子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值