matplotlib入门2

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 2*x + 1

plt.figure(num=1, figsize=(4,5))
plt.plot(x,y,)

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

1、在图片中添加注解

1. 添加点
x0 = 1
y0 = 2*x0 + 1
plt.scatter(x0, y0, s=50, color='b')
2. 添加虚线
k--: k代表黑色, --虚线样式
lw:线宽度
(x0,0)--(x0,y0)生成虚线
plt.plot([x0,x0],[y0,0],'k--',lw=2.5)
3.添加注解
  • 2x+1=y0
  • xycoords:基于data的xy这个点
  • xytext:文字描述--位置
  • textcoords: xytext基于这个
  • arrowprops: 方向线
  • arrowstyle,connectionstyle:箭头样式、弧度
plt.annotate(r'$2x+1=%s$'% y0,
             xy=(x0,y0),xycoords='data',
             xytext=(+30,-30),textcoords='offset points',
             fontsize=16,
             arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=0.2'))
4.给字体定义颜色
  • _i: 角标i
  • _t: 角标t
plt.text(-3.7, 3, r'$li\ hua.\ \mu\sigma_i\ \alpha_t$',
         fontdict={
             'size':12,
             'color':'red',
         })
5.在图片数据量多的时候,处理坐标轴挡住的数据,显示出来
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 0.1*x

plt.figure()
plt.plot(x,y,linewidth=10)
plt.ylim(-2,2)


ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

把坐标轴数值的label取出来,单个设置数据

for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(13)
    label.set_bbox(dict(facecolor='white',edgecolor='None',alpha=0.65))
     

plt.show()
6.柱状图

堆叠柱状图

import matplotlib.pyplot as plt
import numpy as np

# 设置颜色 fc
# 设置标签  tick_label
# 堆叠柱状图

name_list = ['a', 'b', 'c', 'd', 'e','f']
num_list = [1.5, 0.5, 2, 7.8, 5, 1]

# 堆叠柱状图
num_list1 = [1, 2, 1, 1, 1, 3]
plt.bar(range(len(num_list)), num_list,fc='#ff9999',label='boy',tick_label=name_list)
plt.bar(range(len(num_list1)),num_list1, bottom=num_list, label='girl')

plt.legend()

plt.show()

并列柱状图

name_list = ['a', 'b', 'c', 'd']
num_list = [1.5, 0.3, 2, 7]
num_list1 = [1, 2, 3, 4]

x = list(range(len(num_list)))
total_width, n = 0.5, 2
width = total_width / n


plt.bar(x, num_list, width=width, label='A', fc='y')

--# 把b图的x坐标延后了a的宽度-->
for i in range(len(x)):
    x[i] = x[i] + width
    
plt.bar(x, num_list1,width=width, label='B', tick_label=num_list, fc='r')

plt.legend()
plt.show()

条形柱状图

plt.barh(range(len(name_list)), num_list, tick_label = name_list)

你可能感兴趣的:(python,ubuntu)