Python reads excel data, draws multiple subgraphs and displays them separately

 Python's Matplotlib library is one of the most widely used data visualization libraries. As a low-level drawing tool, it is highly customizable. Using Matplotlib, you can plot your data using a variety of chart types, including line charts, bar charts, pie charts, and scatter plots, and you can plot single charts and plot multiple charts.

Draw a single graph

In this column, the drawing method of a single picture and the detailed design of the picture have been explained in detail. Click the link to go directly:

Python line chart drawing | Detailed settings with pictures

Draw multiple subplots and display them on one canvas

python reads data in excel and draws multiple subgraphs and groups of graphs on one canvas

The difference between fig and axis

fig, ax = plt.subplots(x,y,z)It is a more orthodox drawing method (parameters x, y, z represent the zth graph in row x, y column), specify figure and axes, and then operate axes separately (add and modify chart elements)

fig is equivalent to a large canvas, ax is equivalent to a small sub-picture, and a canvas can have one or more sub-pictures

Draw multiple graphics

        Once you know how to do it, you can draw multiple diagrams. Similarly, Matplotlib allows drawing multiple graphs in the form of a grid, which can be solved through the following function

1. Use the subplot() function

2. Use the subplots() function

Use the subplot() function

To make multiple plots using the subplot() function in the pyplot module, you need to perform two steps:

Import code:

import matplotlib.pyplot as plt

First, you need to call the subplot() function with three parameters: (1) the number of rows in the grid, (2) the number of columns in the grid, and (3) the position or axis used for plotting, such as: subplot(3 ax = plt.subplots(x,y,z), 1,1) tells the Python interpreter that the next plot should be drawn in a grid containing 3 rows and 1 column, and that the plot should appear at the first position in the grid (row 1, column 1). The order of drawing positions is first from left to right, then from top to bottom.

After executing the subplot() command, just call the corresponding function or chart type that you want to plot using the pyplot module. For example, the following script uses the plot() method to create a line chart. The key points have been clearly explained and you can directly enter the code:

Complete code

# -*- coding: utf-8 -*-
"""
Created on Sat May  6 11:35:21 2023

@author: ypzhao
"""

import pandas as pd
import numpy as np
import xlsxwriter as xw
import matplotlib.pyplot as plt
from PIL import Image

excel = pd.read_excel("C:/Users/ypzhao/Desktop/电机数据/电机参数.xlsx")
data = pd.DataFrame(excel)

t = data['时间']
T1 = data['转矩1']
S1 = data['转速1']
P1 = data['功率1']

T2 = data['转矩2']
S2 = data['转速2']
P2 = data['功率2']

font = {'family': 'Times New Roman','size': 20}
font_1 = {'family': 'Times New Roman','size': 24}


# 画第1个图:折线图
fig, ax1 = plt.subplots(figsize=(12,8),dpi=1200)


# ax1=fig.add_subplot(3,1,1)
# fig.tight_layout()
ax1.plot(t,T1,marker = "",markersize=1,alpha=.8,color='y',
          linewidth=1,label='Control',markeredgecolor='green',)
ax1.plot(t,T2,marker = "",markersize=1,alpha=.7,
          linewidth=1,label='Uncontrol',markeredgecolor='blue',)
ax1.axis([0, 2100, -250, 750])   #X、Y轴区间

plt.tick_params(labelsize=20)
labels = ax1.get_xticklabels() + ax1.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
plt.rcParams["font.family"] = "Times New Roman"  #全图字号新罗马字体

#rcParams['font.sans-serif']=['SimHei']   #用来正常显示中文标签
#rcParams['axes.unicode_minus']=False  #用来正常显示负号
#或者等价地写为:
#rc('font',family='SimHei') #用来正常显示中文标签
#rc('axes',unicode_minus=False) #用来正常显示负号



plt.legend(ncol=2,frameon=False,prop=font)
# 设置右和上边框是否可见
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
plt.xlabel('Times/s',font_1)
plt.ylabel('Torque/N·m',font_1)
plt.savefig('转矩图.jpg',dpi=1200) #保存为图片png格式

# 画第2个图:转速与时间的关系图

fig, ax2 = plt.subplots(figsize=(12,8),dpi=1200)
fig.tight_layout()
ax2.plot(t,S1,marker = "",markersize=1,alpha=.8,
          linewidth=1,label='Control',markeredgecolor='lightgary',)
ax2.plot(t,S2,marker = "",markersize=1,alpha=.4,color='g',
          linewidth=1,label='Uncontrol',markeredgecolor='maroon',)
plt.tick_params(labelsize=20)
labels = ax2.get_xticklabels() + ax2.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
plt.rcParams["font.family"] = "Times New Roman"  #全图字号新罗马字体
plt.legend(ncol=2,frameon=False,prop=font)
# 设置右和上边框是否可见
ax2.axis([0, 2100, 0, 3000])   #X、Y轴区间

ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
plt.xlabel('Times/s',font_1)
plt.ylabel('r/min',font_1)
plt.savefig('转速图.jpg',dpi=1200) #保存为图片png格式

# 画第3个图:饼图
fig, ax3 = plt.subplots(figsize=(12,8),dpi=1200)
ax3.plot(t,P1,marker = "",markersize=1,alpha=.8,
          linewidth=1,label='Control',markeredgecolor='green',)
ax3.plot(t,P2,marker = "",markersize=1,alpha=.8,
          linewidth=1,label='Uncontrol',markeredgecolor='blue',)
ax3.axis([0, 2100, -50, 105])   #X、Y轴区间

plt.tick_params(labelsize=20)
labels = ax3.get_xticklabels() + ax3.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
plt.rcParams["font.family"] = "Times New Roman"  #全图字号新罗马字体
plt.legend(ncol=2,frameon=False,prop=font)
# 设置右和上边框是否可见
ax3.spines['right'].set_visible(False)
ax3.spines['top'].set_visible(False)
plt.xlabel('Times/s',font_1)
plt.ylabel('Power/kW',font_1)

plt.savefig('功率.jpg',dpi=1200) #保存为图片png格式
# plt.savefig('电机数据.png',dpi=1200) #保存为图片png格式
# plt.savefig('电机数据.tif',dpi=1200) #保存为图片png格式
# plt.savefig('电机数据.eps',dpi=1200) #保存为图片png格式
# plt.savefig('电机数据.pdf',dpi=1200) #保存为图片png格式

# file_path ='电机数据.jpg'
# # 获取图片大小
# img = Image.open(file_path)
# imgSize = img.size  #大小/尺寸
# w = img.width       #图片的宽
# h = img.height      #图片的高
# f = img.format      #图像格式
# img.close
# print(imgSize)
# print(w, h, f)

operation result 

4fe5090a972049158b4df7a63873447f.jpeg

8bee0989c72245e981c2c37ec20219b7.jpeg

Source data and code access link:

Python multi-subgraph drawing data and source code 

Guess you like

Origin blog.csdn.net/m0_58857684/article/details/130605058