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开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑