python画图代码-常用备查【散点图+拟合曲线+双轴折线图】

本文主要是介绍python画图代码-常用备查【散点图+拟合曲线+双轴折线图】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

散点图

导入库

下同

import matplotlib.pyplot as plt
import pandas as pd
from io import BytesIO
import base64

准备模拟数据

# Using Chinese characters as column names
columns = ['A', 'B', 'C', 'D','E', 'F', 'G', 'H']
# Since we cannot extract the actual data from the image, we will create scatter plots with mock data.
# Please note that the values used here are randomly generated and do not correspond to any real dataset.# We'll use numpy to generate the random data
import numpy as np# Number of observations
n = 50# Mock data generation
np.random.seed(0)  # For reproducibility
mock_data = {'A': np.random.uniform(1000, 10000, n),'B': np.random.uniform(1, 100, n),'C': np.random.uniform(10, 1000, n),'D': np.random.uniform(50, 500, n),'E': np.random.uniform(10, 200, n),'F': np.random.uniform(5000, 50000, n),'G': np.random.uniform(100, 1000, n),'H': np.random.uniform(5, 100, n),'I': np.random.uniform(0, 100, n)
}# Create a DataFrame from the mock data
df_mock = pd.DataFrame(mock_data)

设置字体

plt.rcParams['font.sans-serif']=['SimHei'] #显示中文

# Create a scatter plot for each x variable against '省域CEI'
plt.style.use('grayscale')  # Use grayscale style
fig, axes = plt.subplots(4, 2, figsize=(15, 20))  # Prepare a grid for the plots
# 如果不想一次性出6个图,改上面的代码
# Flatten the axes array for easy iteration
axs = axes.flatten()# Loop through each x variable and create a scatter plot
for idx, x in enumerate(columns):axs[idx].scatter(df_mock[x], df_mock['I'], edgecolor='black')axs[idx].set_title(f'示例A-{x}', fontsize=20)axs[idx].set_xlabel(x, fontsize=15)axs[idx].set_ylabel('Y', fontsize=15)axs[idx].tick_params(axis='both', which='major', labelsize=12)axs[idx].grid(True)# Adjust layout so titles and labels don't overlap
plt.tight_layout()
plt.show()

在这里插入图片描述

散点图+拟合曲线

# Based on the new requirement, we will add a linear regression fit line to each scatter plot.
# Additionally, we will save the plots to the local filesystem.from sklearn.linear_model import LinearRegression# Create a Linear Regression model
model = LinearRegression()# Function to create scatter plot with regression line
def plot_with_fit_line(x, y, title, xlabel, ylabel):# Fit the modelmodel.fit(x[:, np.newaxis], y)# Get the linear fit linexfit = np.linspace(x.min(), x.max(), 1000)yfit = model.predict(xfit[:, np.newaxis])# Plot the dataplt.scatter(x, y, c='grey', edgecolors='black', label='Data')# Plot the fit lineplt.plot(xfit, yfit, color='black', linewidth=2, label='Fit line')# Title and labels#plt.title(title, fontsize=20)plt.xlabel(xlabel, fontsize=15)plt.ylabel(ylabel, fontsize=15)# Font size for ticksplt.xticks(fontsize=15)plt.yticks(fontsize=15)# Grid and legendplt.grid(False)#plt.legend()# Save the figureplt.savefig(f'C:/Users/12810/Desktop/结果图/{xlabel}_vs_{ylabel}.png')# 取消灰色网格背景# Show the plotplt.show()# Return the path of the saved plotreturn f'C:/Users/12810/Desktop/结果图/{xlabel}_vs_{ylabel}.png'# Paths where plots will be saved
saved_plots = []# Create and save a scatter plot with a fit line for each x variable against '省域CEI'
for col in columns:# Generate the plot and get the path where it's savedplot_path = plot_with_fit_line(df_mock[col].values, df_mock['省域CEI'].values, f"{col}与省域CEI的散点图", col, '省域CEI')# Store the pathsaved_plots.append(plot_path)# Show the paths where the plots are saved
saved_plots

在这里插入图片描述

双坐标轴-折线图

import pandas as pd
import matplotlib.pyplot as pltfrom matplotlib.font_manager import FontPropertiesdf_mock # 读取数据# Set the font properties for displaying Chinese characters
plt.rcParams['font.sans-serif']=['SimHei'] #显示中文
# Use the 'grayscale' style
plt.style.use('grayscale')# Create a new figure and a twin axis
fig, ax1 = plt.subplots()
x_lable=r'AAA'
y_lable = r'BBB'# Plot the first line on the primary y-axis
ax1.plot(df_mock.index, df_mock['A'], color='black', marker='o', label=x_lable)
ax1.set_xlabel('时间(年)')
ax1.set_ylabel(x_lable, color='black')
ax1.tick_params(axis='y', colors='black')# Rotate the x-axis labels
for label in ax1.get_xticklabels():label.set_rotation(45)label.set_fontproperties(font)# Create a second y-axis to plot the second line
ax2 = ax1.twinx()
ax2.plot(df_mock.index, df_mock["B"], color='red', marker='s', label=y_lable)
ax2.set_ylabel(y_lable, color='grey')
ax2.tick_params(axis='y', colors='grey')# Set the title and show the legend
# plt.title('双轴折线图', fontproperties=font)
ax1.legend(loc='upper left',bbox_to_anchor=(0.5, -0.30), fancybox=True, shadow=True, ncol=3)
ax2.legend(loc='upper right',bbox_to_anchor=(0.5, -0.30), fancybox=True, shadow=True, ncol=3)
# 显示图例,放置在图表外的底部中央# Finally, save the figure to a file
plt.savefig(r'C:\Users\12810\【人口与绿化】.png', bbox_inches='tight',dpi=300)
plt.show()

在这里插入图片描述

这篇关于python画图代码-常用备查【散点图+拟合曲线+双轴折线图】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/867422

相关文章

Python Transformers库(NLP处理库)案例代码讲解

《PythonTransformers库(NLP处理库)案例代码讲解》本文介绍transformers库的全面讲解,包含基础知识、高级用法、案例代码及学习路径,内容经过组织,适合不同阶段的学习者,对... 目录一、基础知识1. Transformers 库简介2. 安装与环境配置3. 快速上手示例二、核心模

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

python实现svg图片转换为png和gif

《python实现svg图片转换为png和gif》这篇文章主要为大家详细介绍了python如何实现将svg图片格式转换为png和gif,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录python实现svg图片转换为png和gifpython实现图片格式之间的相互转换延展:基于Py

Python中的getopt模块用法小结

《Python中的getopt模块用法小结》getopt.getopt()函数是Python中用于解析命令行参数的标准库函数,该函数可以从命令行中提取选项和参数,并对它们进行处理,本文详细介绍了Pyt... 目录getopt模块介绍getopt.getopt函数的介绍getopt模块的常用用法getopt模

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.

Python如何精准判断某个进程是否在运行

《Python如何精准判断某个进程是否在运行》这篇文章主要为大家详细介绍了Python如何精准判断某个进程是否在运行,本文为大家整理了3种方法并进行了对比,有需要的小伙伴可以跟随小编一起学习一下... 目录一、为什么需要判断进程是否存在二、方法1:用psutil库(推荐)三、方法2:用os.system调用

Java的栈与队列实现代码解析

《Java的栈与队列实现代码解析》栈是常见的线性数据结构,栈的特点是以先进后出的形式,后进先出,先进后出,分为栈底和栈顶,栈应用于内存的分配,表达式求值,存储临时的数据和方法的调用等,本文给大家介绍J... 目录栈的概念(Stack)栈的实现代码队列(Queue)模拟实现队列(双链表实现)循环队列(循环数组

使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)

《使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)》PPT是一种高效的信息展示工具,广泛应用于教育、商务和设计等多个领域,PPT文档中常常包含丰富的图片内容,这些图片不仅提升了... 目录一、引言二、环境与工具三、python 提取PPT背景图片3.1 提取幻灯片背景图片3.2 提取

usb接口驱动异常问题常用解决方案

《usb接口驱动异常问题常用解决方案》当遇到USB接口驱动异常时,可以通过多种方法来解决,其中主要就包括重装USB控制器、禁用USB选择性暂停设置、更新或安装新的主板驱动等... usb接口驱动异常怎么办,USB接口驱动异常是常见问题,通常由驱动损坏、系统更新冲突、硬件故障或电源管理设置导致。以下是常用解决