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

相关文章

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re