python数据可视化 matplotlib(3)小白 完善统计图形 (如何调整刻度范围和刻度标签、如何在统计图形里添加表格等、如何在matplotlib上设置坐标轴的刻度样式)

如何在matplotlib输入数学表达式

这里使用的是matplotlib自带的TeX实现数学表达式输入,通过"$ s i n ( x ) sin(x) sin(x)$"模式,将表达式 s i n ( x ) sin(x) sin(x)嵌入中间。
在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
x=np.linspace(-2*np.pi,2*np.pi,200)
y=np.sin(x)
y1=np.cos(x)
plt.plot(x,y,label=r"$\sin(x)$",color='red')  # 这个非斜体
plt.plot(x,y1,'b--',label="$cos(x)$") #这个是斜体
plt.title("正弦函数和余弦函数的折线图")
plt.legend()
plt.show()

如何在matplotlib更改图例样式

在这里插入图片描述

loc参数设置upperlowercenter
right147
left236
center9810

怎么说呢,人嘛年少无知总是想给他排序,然鹅!!毫无规律,直接写英文吧,别用数值代替了!!!
loc=2loc="upper left"是等价的
线框位置参数:bbox_to_anchhor
线框阴影:shadow=True
线框圆角处理参数:fancybox=True
线框一行4个:ncol=4

import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
x=np.arange(0,2,0.1)
y=np.power(x,1)
y1=np.power(x,2)
y2=np.power(x,3)
y3=np.power(x,4)
plt.plot(x,y,ls="-",lw=2,label="$x$")
plt.plot(x,y1,ls="--",lw=2,label="$x^{2}$")
plt.plot(x,y2,ls=":",lw=2,label="$x^{3}$")
plt.plot(x,y3,ls="-.",lw=2,label="$x^{4}$")
plt.title("正弦函数和余弦函数的折线图")
plt.legend(loc=2,bbox_to_anchor=(0.05,0.95),ncol=4,title="函数",shadow=True,fancybox=True)
plt.show()

如何在matplotlib上函数分区

在这里插入图片描述
子区函数:subplot(),这个函数专门用来绘制几何形状相同的网格区域,子区顾名思义就是将画布分为若干个子画布。
子区函数subplot(211)subplot(212)在一个2行1列的画布格式上分别为第一个图形,和第二个图形。
进一步地,子区函数subplot(515)就会是一个5行1列的画布的第5行图形,该图形占一行;子区函数subplot(529)就会是一个5行2列的画布同样位于第5行。

import numpy as np
import matplotlib.pyplot as plt
def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 3.0, 0.01)
ax2 = plt.subplot(221)
ax2.margins(2, 2)           # Values >0.0 zoom out
ax2.plot(t1, f(t1))
ax2.set_title('Zoomed out')
ax3 = plt.subplot(222)
ax3.margins(x=0, y=-0.25)   # Values in (-0.5, 0.0) zooms in to center
ax3.plot(t1, f(t1))
ax3.set_title('Zoomed in')
ax1 = plt.subplot(212)
ax1.margins(0.05)           # Default margin is 0.05, value 0 means fit
ax1.plot(t1, f(t1))
plt.show()

在这里插入图片描述

ax2 = plt.subplot(221)
ax2.margins(2, 2)           # Values >0.0 zoom out
ax2.plot(t1, f(t1))
ax3 = plt.subplot(222)
ax3.margins(x=0, y=-0.25)   # Values in (-0.5, 0.0) zooms in to center
ax3.plot(t1, f(t1))
ax1 = plt.subplot(212)
ax1.margins(0.05)           # Default margin is 0.05, value 0 means fit
ax1.plot(t1, f(t1))

ax6 = plt.subplot(212)
ax6.margins(0.05)           # Default margin is 0.05, value 0 means fit
ax6.plot(t2, f(t2))
ax4 = plt.subplot(221)
ax4.margins(2, 2)           # Values >0.0 zoom out
ax4.plot(t2, f(t2))
ax5 = plt.subplot(222)
ax5.margins(x=0, y=-0.25)   # Values in (-0.5, 0.0) zooms in to center
ax5.plot(t2, f(t2))
plt.show()

如何在matplotlib上逆序设置坐标轴

通过使用函数xlim()将刻度标签值降序排列。就是xlim(xmin,xmax)的顺序修改为xlim(xmax,xmin)以此实现逆序坐标轴。

如何在matplotlib上设置坐标轴的刻度样式

在这里插入图片描述
从模块ticker导入类AutoMinorLocator, MultipleLocator, FuncFormatter,
通过ax.xaxis.set_major_locator(MultipleLocator(2.5)) 设置主刻度线位置
设置主刻度线位置:MultipleLocator(2.5)
次要刻度线位置:AutoMinorLocator(4)
主刻度样式设置:ax.tick_params()关键字参数

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter
x=np.linspace(0.5,3.6,100)
y=np.sin(x)
fig= plt.figure(figsize=(8,8))
ax=fig.add_subplot(111)
#set x y-major_tick_locator
ax.xaxis.set_major_locator(MultipleLocator(2.5)) # 主刻度线间隔
ax.yaxis.set_major_locator(MultipleLocator(1.0))

#set x y-minor_tick_locator
ax.xaxis.set_minor_locator(AutoMinorLocator(4)) # 分开多少格 等分几个
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

#set x_minor_tick_formatter
def minor_tick(x,pos): # n%n=0;m%n=m(m<n)
    if not x % 1.0:
        return ""
    return "%.2f" %x  #保留两位小数
ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))
#change the appearance of ticks and tick labels
ax.tick_params("y",which="major",
               length=1.0,width=2.0,
               colors="black"
               )    
ax.tick_params(which="minor",
               length=5,width=2.0, 
               labelsize=10,labelcolor='green' # 可以直观看到颜色
               )  
#set x,y_axis_limit
ax.set_xlim(0,4)
ax.set_ylim(0,2)
#plot subplot
ax.plot(x,y,c=(0.25,0.25,1.00),lw=2,zorder=20) #函数那条线
# set grid
ax.grid(linestyle="--",linewidth=1.5,color="black") 

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np
fig= plt.figure(facecolor="#FFFFC1") #背景颜色
ax=fig.add_axes([0.1,0.4,1,1])
for ticklabel in ax.xaxis.get_ticklabels():
    ticklabel.set_color("slateblue")
    ticklabel.set_fontsize(12)
    ticklabel.set_rotation(-90) #倾斜
for tickline in ax.yaxis.get_ticklines():
    tickline.set_color("lightgreen")
    tickline.set_markersize(30)
    tickline.set_markeredgewidth(20)
plt.show()

加水印

在这里插入图片描述

import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
class WatermarkFigure(Figure):
    def __init__(self, *args, watermark=None, **kwargs):
        super().__init__(*args, **kwargs)

        if watermark is not None:
            bbox = dict(boxstyle='square', lw=3, ec='gray', #框框形状 框框粗细 颜色
                        fc=(1, 0.9, .9, .5),  #框内颜色
                        alpha=0.4  #设置0,即可无框框
                        ) 
            self.text(0.5, 0.5, watermark, #水印位置设定
                      ha='center', va='center', rotation=20,
                      fontsize=20, color='gray', alpha=0.5, bbox=bbox)

x = np.linspace(-3, 3, 201)
y = np.tanh(x) + 0.1 * np.cos(5 * x)
plt.figure(FigureClass=WatermarkFigure, watermark='matplotlib')
plt.plot(x, y)

重叠和交叉

在这里插入图片描述
在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-5, 5, 0.01)
y1 = -5*x*x + x + 10
y2 = 5*x*x + x
fig, ax = plt.subplots()
ax.plot(x, y1, x, y2, color='black')
ax.fill_between(x, y1, y2, where=(y2 > y1), facecolor='yellow', alpha=0.5)
ax.fill_between(x, y1, y2, where=(y2 <= y1), facecolor='red', alpha=0.5)
ax.set_title('Fill Between')
plt.show()

'''下一个图'''
x = np.array([0, 1, 2, 3])
y1 = np.array([0.8, 0.8, 0.2, 0.2])
y2 = np.array([0, 0, 1, 1])

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)

ax1.set_title('interpolation=False')
ax1.plot(x, y1, 'o--')
ax1.plot(x, y2, 'o--')
ax1.fill_between(x, y1, y2, where=(y1 > y2), color='C0', alpha=0.3)
ax1.fill_between(x, y1, y2, where=(y1 < y2), color='C1', alpha=0.3)

ax2.set_title('interpolation=True')
ax2.plot(x, y1, 'o--')
ax2.plot(x, y2, 'o--')
ax2.fill_between(x, y1, y2, where=(y1 > y2), color='C0', alpha=0.3,
                 interpolate=True)
ax2.fill_between(x, y1, y2, where=(y1 <= y2), color='C1', alpha=0.3,
                 interpolate=True)
fig.tight_layout()
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值