# 导入包
import matplotlib.pyplot as plt
x = range(2,26,2)
y = [15,13,16,25,21,23,16,19,17,22,12,13]
# 画图
plt.plot(x,y)
# 显示图片
plt.show()
设置图片大小,像素
# 设置图片大小,像素
fig = plt.figure(figsize=(20,8),dpi=80)
保存图片
plt.savefig('mat1.png',dpi=300)
设置刻度标签
# plt.xticks(range(20,50))
plt.xticks([5,10,15,20,15],['lab1','lab2','lab3','lab4','lab5'])
设置标题
plt.title('Is my title',fontsize=20)
添加标签
plt.xlabel('X Label')
plt.ylabel('Y Label')
设置坐标范围
plt.xlim(2, 20)
plt.ylim(10, 20)
设置背景色:可以使用plt.gca().set_facecolor()
函数来设置图形的背景色
import matplotlib.pyplot as plt
import matplotlib
# 设置中文字体
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 或者 ['Microsoft YaHei']
# 绘制图形
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('中文标题')
plt.show()
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
# 加载字体文件
font_path = '/path/to/font.ttf'
font_prop = fm.FontProperties(fname=font_path)
# 设置中文字体
plt.rcParams['font.family'] = font_prop.get_name()
# 绘制图形
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel('X轴', fontproperties=font_prop)
plt.ylabel('Y轴', fontproperties=font_prop)
plt.title('中文标题', fontproperties=font_prop)
plt.show()
import matplotlib.pyplot as plt
import matplotlib
import random
# 设置中文字体
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei']
x = [random.random() for _ in range(20)]
y = [random.random() for _ in range(20)]
plt.scatter(x,y)
plt.xlabel("X")
plt.ylabel("Y")
plt.title('散点图')
plt.show()
plt.bar(x, height, width=0.5)
plt.bar(x, height, color='red')
plt.bar(x, height, color='#FF0000')
plt.bar(x, height, edgecolor='black')
plt.bar(x, height, linewidth=2)
plt.bar(x, height, label='柱状图')
plt.legend()
plt.bar(x, height, alpha=0.5)
plt.bar(x, height, align='edge')
plt.bar(x, height, tick_label=['A', 'B', 'C'])
import matplotlib.pyplot as plt
import matplotlib
import random
# 设置中文字体
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei']
a=['星期一','星期二','星期三','星期四']
b1=[1256,1036,2569,1548]
b2=[2653,2410,1360,3250]
b3=[3562,1548,1254,3654]
bar_width = 0.2
a1 = list(range(len(a)))
a2 = [i+bar_width for i in a1]
a3 = [i+bar_width*2 for i in a1]
plt.xticks(a2[:],a[:])
plt.bar(a1,b1,width=0.2,color='blue')
plt.bar(a2,b2,width=0.2,color='red')
plt.bar(a3,b3,width=0.2,color='green')
plt.show()
import random
import matplotlib.pyplot as plt
# 生成随机数据
data1 = [random.randint(1, 100) for _ in range(100)]
data2 = [random.randint(50, 150) for _ in range(100)]
# 设置直方图的参数
num_bins = 10 # 柱子数量
alpha = 0.5 # 透明度
color1 = 'blue' # 颜色1
color2 = 'red' # 颜色2
# 绘制直方图
plt.hist(data1, bins=num_bins, alpha=alpha, color=color1, label='Data 1')
plt.hist(data2, bins=num_bins, alpha=alpha, color=color2, label='Data 2')
# 添加图例,标签和标题
plt.legend()
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Comparison Histogram')
plt.grid()
plt.show()