matplotlib supplement

设置备注
plt.annotate('文本', xy=目标位置, xycoords=目标位置的坐标系, xytext=文本的位置,textcoords='offset points',fontsize, arrowprops=箭头属性)

设置文本
plt.text(xo, yo_cos,
         '文本内容',
         ha='center',
         va='top', 
         fontsize=9,
         rotation=-12,
         color="black")

颜色填充
# 可以得到cosy 和 siny之间交集的填充颜色
plt.fill_between(x, cosy, siny, where=cosy<siny, color='green', )

折线图
plt.plot(x, y, label='XXXX', linestyle='--', linewidth=3, color='blue', marker='o', zorder=1) 
# marker = "o", "+", "x", "p"
# zorder = 排序方式值越大越在上边

条形图
plt.bar(x,y, ec='red', fc='skyblue',)

等高线
plt.contourf(x, y, z, 12, cmap='jet')

散点图
plt.scatter(x, y, s=60, c=d, cmap='cool',marker="+")
# marker = "o", "+", "x", "p"
# edgecolors 设置圆边的颜色
# facecolor 设置背景颜色

热力图
plt.imshow(z, cmap='jet', origin='lower')

饼图
plt.pie([21, 32, 23, 45, 13], explode=[0,0,0.5,0,0], labels=['python', 'js', 'c++', "c", 'php'], autopct='%.1f%%',shadow=True)

from matplotlib import pyplot
import numpy

x = numpy.arange(1,20)
y = x*4+2
print(x)
print(y)
pyplot.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
pyplot.rcParams['axes.unicode_minus']=False #用来正常显示负号
pyplot.title("Matplotlib demo")
pyplot.xlabel("x 值")
pyplot.ylabel("y 值")
pyplot.plot(x, y)
pyplot.show()

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

显示中文并让字体倾斜

from matplotlib import pyplot as plot
import numpy

plot.rcParams['font.sans-serif'] = ['SimHei']
plot.rcParams['font.family'] = 'sans-serif'
plot.figure("one")
x = ['中文','日文', '韩文', '英文', '德文' , '西班牙', '意大利']
# 随机生成 0.5 - 1 之间 12个数
y = numpy.array([1,2,3,4,5,6,7])
for _x, _y in zip(x, y):
    plot.text(_x, _y, "%.2f" % _y, ha="center", va="bottom", size=8)
plot.xlabel("xx",)
plot.ylabel("yy",)
# 设置字体倾斜
plot.xticks(rotation=-45)
plot.bar(x, y, ec="white", fc="red", label="x's method")
plot.show()

自动调整xy坐标随着数据的多少合理分配宽度和图片大小,不会让数据拥挤

label and value 是我们的list 数据

mp.figure("BalanceOne", (18, 10))
mp.title("利润表" + "->")
mp.bar(label, value, color='lightblue')
# 加网格
mp.grid()
# 设置x轴标数量,字体大小,旋转角度
# x值一般情况可以不用
#x = numpy.arange(len(value))
mp.xticks(fontsize=8)
for a, b in zip(label, value):
    mp.text(a, b + 0.05, '%.2e' % b, ha='center', va='bottom', fontsize=12, rotation=45, color="green")
# 设置X坐标轴最大化拉伸
# gca获取当前图的句柄 设置x坐标的外边距
mp.gca().margins(x=0.005)
# gcf获取当前图表边框的句柄
mp.gcf().canvas.draw()
tl = mp.gca().get_xticklabels()
maxsize = max([t.get_window_extent().width for t in tl])
m = 0.2  # inch margin
s = maxsize / mp.gcf().dpi * len(value) + 2 * m
margin = m / mp.gcf().get_size_inches()[0]
mp.gcf().subplots_adjust(left=margin, right=1. - margin)
mp.gcf().set_size_inches(s, mp.gcf().get_size_inches()[1])
# 保存
mp.savefig(__file__ + "profit.jpg")
mp.show()

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

matplotlib.pyplot.plot 参数

import matplotlib.pyplot as plt
help(plt.plot)
以下是对帮助文档重要部分的翻译:

plot函数的一般的调用形式:

#单条线:
plot([x], y, [fmt], data=None, **kwargs)
#多条线一起画
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
可选参数[fmt] 是一个字符串来定义图的基本属性如:颜色(color),点型(marker),线型(linestyle),

具体形式  fmt = '[color][marker][line]'

fmt接收的是每个属性的单个字母缩写,例如:

plot(x, y, 'bo-')  # 蓝色圆点实线
若属性用的是全名则不能用*fmt*参数来组合赋值,应该用关键字参数对单个属性赋值如:

plot(x,y2,color='green', marker='o', linestyle='dashed', linewidth=1, markersize=6)

plot(x,y3,color='#900302',marker='+',linestyle='-')

常见的颜色参数:**Colors**


 
也可以对关键字参数color赋十六进制的RGB字符串如 color='#900302'

    =============    ===============================
    character        color
    =============    ===============================
    ``'b'``          blue 蓝
    ``'g'``          green 绿
    ``'r'``          red 红
    ``'c'``          cyan 蓝绿
    ``'m'``          magenta 洋红
    ``'y'``          yellow 黄
    ``'k'``          black 黑
    ``'w'``          white 白
    =============    ===============================
 点型参数**Markers**,如:marker='+' 这个只有简写,英文描述不被识别
=============    ===============================
    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
    ``'s'``          square marker
    ``'p'``          pentagon marker
    ``'*'``          star marker
    ``'h'``          hexagon1 marker
    ``'H'``          hexagon2 marker
    ``'+'``          plus marker
    ``'x'``          x marker
    ``'D'``          diamond marker
    ``'d'``          thin_diamond marker
    ``'|'``          vline marker
    ``'_'``          hline marker
    =============    ===============================
线型参数**Line Styles**,linestyle='-'

    =============    ===============================
    character        description
    =============    ===============================
    ``'-'``          solid line style 实线
    ``'--'``         dashed line style 虚线
    ``'-.'``         dash-dot line style 点画线
    ``':'``          dotted line style 点线
    =============    ===============================
样例1

函数原型:matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)
>>> plot('xlabel', 'ylabel', data=obj)
解释:All indexable objects are supported. This could e.g. be a dict, a pandas.DataFame or a structured numpy array.
data 参数接受一个对象数据类型,所有可被索引的对象都支持,如 dict 等
import matplotlib.pyplot as plt  
import numpy as np
'''read file 
fin=open("para.txt")
a=[]
for i in fin:
  a.append(float(i.strip()))
a=np.array(a)
a=a.reshape(9,3)
'''
a=np.random.random((9,3))*2 #随机生成y
 
y1=a[0:,0]
y2=a[0:,1]
y3=a[0:,2]
 
x=np.arange(1,10)
 
ax = plt.subplot(111)
width=10
hight=3
ax.arrow(0,0,0,hight,width=0.01,head_width=0.1, head_length=0.3,length_includes_head=True,fc='k',ec='k')
ax.arrow(0,0,width,0,width=0.01,head_width=0.1, head_length=0.3,length_includes_head=True,fc='k',ec='k')
 
ax.axes.set_xlim(-0.5,width+0.2)
ax.axes.set_ylim(-0.5,hight+0.2)
 
plotdict = { 'dx': x, 'dy': y1 }
ax.plot('dx','dy','bD-',data=plotdict)
 
ax.plot(x,y2,'r^-')
ax.plot(x,y3,color='#900302',marker='*',linestyle='-')
 
plt.show()


样例2,

import matplotlib.pyplot as plt  
import numpy as np  
  
x = np.arange(0, 2*np.pi, 0.02)  
y = np.sin(x)  
y1 = np.sin(2*x)  
y2 = np.sin(3*x)  
ym1 = np.ma.masked_where(y1 > 0.5, y1)  
ym2 = np.ma.masked_where(y2 < -0.5, y2)  
  
lines = plt.plot(x, y, x, ym1, x, ym2, 'o')  
#设置线的属性
plt.setp(lines[0], linewidth=1)  
plt.setp(lines[1], linewidth=2)  
plt.setp(lines[2], linestyle='-',marker='^',markersize=4)  
#线的标签
plt.legend(('No mask', 'Masked if > 0.5', 'Masked if < -0.5'), loc='upper right')  
plt.title('Masked line demo')  
plt.show()  

---------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值