Matplotlib属性大变身,让你的图表穿上时尚外衣,数据也能颜值爆表!
1.导包
# 导包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 如果浏览器不显示图片,就需要加上这句话
%matplotlib inline
# 让图片中可以显示中文
plt.rcParams['font.sans-serif'] = "SimHei"
# 让图片中可以显示负号
plt.rcParams["axes.unicode_minus"] = False
# 支持svg矢量图
%config Inlinebackend.figure_format = "svg"
2.绘图基本属性
- legend():图例
# 第一种方式
plt.figure(figsize=(6, 4))
x = np.linspace(0, 2*np.pi)
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
# 图例
plt.legend()
<matplotlib.legend.Legend at 0x2b222b11450>
# 第二种方式
plt.figure(figsize=(6, 4))
x = np.linspace(0, 2*np.pi)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
# 图例
# ["sin", "cos"]:显示的图例
# fontsize:图例大小
# loc:显示位置
# ncol:显示成几列
# bbox_to_anchor:图例的具体位置(x, y, width, height)
plt.legend(["sin", "cos"], fontsize=12, loc="center", ncol=2, bbox_to_anchor=[0, 1, 1, 0.2])
<matplotlib.legend.Legend at 0x2b224435150>
3.线条属性
- color 颜色
- linestyle 样式
- linewidth 宽度
- alpha 透明度
- marker 标记
- mfc:marker face color 标记的背景颜色
plt.figure(figsize=(6,4))
x = np.linspace(0, 2*np.pi, 20)
y1 = np.sin(x)
y2 = np.cos(x)
"""
**Markers**
============= ===============================
character description
============= ===============================
``'.'`` point marker
``','`` pixel marker
``'o'`` circle marker
``'v'`` triangle_down marker
``'^'`` triangle_up marker
``'<'`` triangle_left marker
``'>'`` triangle_right marker
``'1'`` tri_down marker
``'2'`` tri_up marker
``'3'`` tri_left marker
``'4'`` tri_right marker
``'8'`` octagon marker
``'s'`` square marker
``'p'`` pentagon marker
``'P'`` plus (filled) marker
``'*'`` star marker
``'h'`` hexagon1 marker
``'H'`` hexagon2 marker
``'+'`` plus marker
``'x'`` x marker
``'X'`` x (filled) marker
``'D'`` diamond marker
``'d'`` thin_diamond marker
``'|'`` vline marker
``'_'`` hline marker
============= ===============================
**Line Styles**
============= ===============================
character description
============= ===============================
``'-'`` solid line style
``'--'`` dashed line style
``'-.'`` dash-dot line style
``':'`` dotted line style
============= ===============================
Example format strings::
'b' # blue markers with default shape
'or' # red circles
'-g' # green solid line
'--' # dashed line with default color
'^k:' # black triangle_up markers connected by a dotted line
**Colors**
The supported color abbreviations are the single letter codes
============= ===============================
character color
============= ===============================
``'b'`` blue
``'g'`` green
``'r'`` red
``'c'`` cyan
``'m'`` magenta
``'y'`` yellow
``'k'`` black
``'w'`` white
============= ===============================
"""
# c:color颜色
# marker:标记
# ls: line style 线样式
# lw: line width 线宽度
# label:标签
# mfc:marker face color 标记的背景颜色
# markersize:标记大小
# markeredgecolor:标记(点)的边缘颜色
# markeredgewidth:标记(点)边缘的宽度
# alpha:透明度(0~1)
plt.plot(x, y1, c="r", marker="o", ls="--", lw=1, label="sinx", mfc="y")
plt.plot(x, y2, c="b", marker="*", ls="-", lw=2, label="cosx", mfc="w", markersize=10)
plt.plot(x, y1-y2, c="y", marker="^", ls="-", lw=3, label="sinx-cosx", mfc="b", markersize=10)
plt.plot(x, y1+y2, c="orange", marker=">", ls="-.", lw=4, label="sinx+cosx", mfc="y", markersize=10, markeredgecolor="green", markeredgewidth=2, alpha=0.5)
# 图例
plt.legend()
<matplotlib.legend.Legend at 0x218151a2f50>
4.坐标轴刻度
- xticks
- yticks
plt.figure(figsize=(5, 3))
x = np.linspace(0, 10)
y = np.sin(x)
plt.plot(x, y)
plt.xticks(np.arange(0, 11, 1))
plt.yticks([-1, 0, 1])
plt.show()
plt.figure(figsize=(5, 3))
x = np.linspace(0, 10)
y = np.sin(x)
plt.plot(x, y)
# ticks:刻度值,刻度大小
# labels:显示刻度标签
# ha:水平对齐方式(left,right,center)
plt.xticks(ticks=np.arange(0, 11, 1), fontsize=20, color="red")
plt.yticks(ticks=[-1, 0, 1], labels=["min", "0", "max"], fontsize=20, color="blue", ha="right")
plt.show()
5.坐标轴范围
- xlim
- ylim
plt.figure(figsize=(5, 3))
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
plt.plot(x, y, c="r")
plt.xlim(-2, 8)
plt.ylim(-2, 2)
plt.show()
6.坐标轴配置
- axis
plt.figure(figsize=(5, 3))
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
plt.plot(x, y, c="r")
# 设置坐标轴的取值范围:[xmin, xmax, ymin, ymax]
plt.axis([-2, 8, -2, 2])
plt.show()
plt.figure(figsize=(5, 3))
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
plt.plot(x, y, c="r")
# option
# on:默认值,不写效果一样
plt.axis("on")
plt.show()
plt.figure(figsize=(5, 3))
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
plt.plot(x, y, c="r")
# option
# off: 不显示坐标轴
plt.axis("off")
plt.show()
plt.figure(figsize=(5, 3))
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
plt.plot(x, y, c="r")
# option
# equal: 让x轴和y轴,刻度距离相同
plt.axis("equal")
plt.show()
plt.figure(figsize=(5, 3))
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
plt.plot(x, y, c="r")
# option
# scaled: 自动缩放坐标轴和图片匹配
plt.axis("scaled")
plt.show()
plt.figure(figsize=(5, 3))
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
plt.plot(x, y, c="r")
# option
# tight: 紧凑型自动适配图片
plt.axis("tight")
plt.show()
plt.figure(figsize=(5, 3))
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
plt.plot(x, y, c="r")
# option
# square: 让画布呈现正方形,x轴和y轴宽高一致
plt.axis("square")
plt.show()
7.标题和网格线
- title
- grid
plt.figure(figsize=(5, 3))
x = np.linspace(0, 10)
y = np.sin(x)
plt.plot(x, y, c="r")
# 图的标题
# fontsize:设置标题大小
# loc:设置标题位置(left,right,center),默认居中
plt.title("sin曲线", fontsize=15, loc="center")
# 设置父标题
plt.suptitle("父标题", y=1.1, fontsize=20)
# 网格线
# ls:line style
# lw:line width
# c: color
# axis:让哪个轴显示网格线,(不要写该参数,默认X和Y轴都显示)
plt.grid(ls="--", lw=0.5, c="gray", axis="y")
8.标签
- xlabel
- ylabel
plt.figure(figsize=(5, 3))
x = np.linspace(0, 10)
y = np.sin(x)
plt.plot(x, y)
# 坐标轴的标签
# fontsize:设置标签大小
# rotation:设置标签旋转的角度
plt.xlabel("y=sin(x)", fontsize=20, rotation=30)
# horizontalalignment:对齐方式(left,right,center),简称ha
plt.ylabel("y=sin(x)", fontsize=20, rotation=30, horizontalalignment="right")
plt.title("正弦曲线")
plt.show()
9.文本
- text
plt.figure(figsize=(5, 3))
x = np.linspace(0, 10, 10)
y = np.array([60, 30, 20, 90, 40, 60, 50, 80, 70, 30])
plt.plot(x, y, ls="--", marker="o")
# 画文字
# x:x轴坐标
# y:y轴坐标
# s:文本内容
# fontsize:文本大小
# color:文本颜色
# ha:水平对齐方式(left,right,center)
# va:垂直对齐方式(top,bottom,center)
for a, b in zip(x, y):
plt.text(x=a+0.3, y=b+1, s=b, fontsize=10, color="r", ha="center", va="center")
10.注释
- annotate
plt.figure(figsize=(5, 3))
x = np.linspace(0, 10, 10)
y = np.array([60, 30, 20, 90, 40, 60, 50, 80, 70, 30])
plt.plot(x, y, ls="--", marker="o")
# 注释:标注
# text:标注内容
# xy:标准的坐标点,箭头指向的位置
# xytext:标准内容的位置
# arrowprops:箭头线的宽度
# headwidth:箭头头部的宽度
# facecolor:箭头的背景颜色
plt.annotate(text="最高销量",xy=(3.2, 90), xytext=(1, 80), arrowprops={"width":1, "headwidth":8, "facecolor":"blue"})
Text(1, 80, '最高销量')
11.保存图片
- savefig
# 第一种方式
plt.figure(figsize=(5, 3))
x = np.linspace(0, 2*np.pi)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
plt.savefig("sincos.png")
# 第二种方式
fig = plt.figure(figsize=(5, 3))
x = np.linspace(0, 2*np.pi)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
# fname:图片名称(文件扩展名支持:png,jpg)
# dpi:保存图片的像素密度
# facecolor:背景颜色
# pad_inches:内边距
fig.savefig(fname="sincos2.png", dpi=100, facecolor='pink', pad_inches=1)
原文地址:https://blog.csdn.net/luorongxi123/article/details/140595033
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!