# 导入包 import pandas as pd import matplotlib as mpl import numpy as np import matplotlib.pyplot as plt import seaborn as sns plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus']=False mpl.use('TkAgg') # 导入数据 df = pd.read_csv(r'C:\Users\F\Desktop\3变量\data/CS2_35.csv') df_coor = df.corr() print(df_coor) fig, ax = plt.subplots(figsize=(8,6),facecolor='w') # 指定颜色带的色系 sns.heatmap(df.corr(),annot=True, vmax=1, square=True, cmap="Blues", fmt='.3g') plt.title('CS2_38') plt.show() fig.savefig('./df_corr.png',bbox_inches='tight',transparent=True),帮我解释下这个代码用的方法和原理
时间: 2024-01-12 22:03:26 浏览: 232
这段代码主要是用于数据分析和可视化,使用了一些常用的Python数据分析和可视化包,具体解释如下:
1. 导入包:分别导入了 pandas、matplotlib、numpy、seaborn 等常用的数据分析和可视化包,其中 plt.rcParams['font.sans-serif'] = ['SimHei'] 和 plt.rcParams['axes.unicode_minus']=False 用于解决中文显示和负号显示的问题。
2. 导入数据:使用 pandas 读取了一个 csv 格式的数据文件,存储在名为 df 的 DataFrame 对象中。
3. 计算相关系数矩阵:使用 df.corr() 计算了 DataFrame 对象中各列之间的相关系数,生成了一个相关系数矩阵 df_coor。
4. 生成热力图:使用 seaborn 库的 heatmap() 函数生成了一个热力图,该函数的参数包括要绘制的数据、是否显示相关系数值、颜色带色系、矩阵元素格式等。
5. 输出和保存热力图:使用 matplotlib 库的 subplots() 函数生成一个图像窗口,使用 plt.title() 函数设置图像标题,最后使用 plt.show() 函数输出图像并使用 fig.savefig() 函数保存图像到本地磁盘。
总的来说,这段代码使用了 pandas、matplotlib、numpy、seaborn 等常用的数据分析和可视化工具,通过计算相关系数矩阵和生成热力图的方式,展示了数据变量之间的相关程度和相关性强弱,从而有助于数据分析和决策。
相关问题
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from pandas_profiling import ProfileReport from sklearn import datasets from mpl_toolkits.mplot3d import Axes3D from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler data=pd.read_csv('H:/analysis_results/mean_HN.csv') columns=['folder', 'volume', 'convex_volume', 'surface_area','length','max_width', 'max_depth'] data.head() values=data.iloc[:,1:7] correlation=values.corr() fig,ax=plt.subplots(figsize=(12,10)) sns.heatmap(correlation,annot=True,annot_kws={'size':16},cmap='Reds',square=True,ax=ax) sns.pairplot(data,hue='folder') plt.show()如何保存这两张图
你可以在代码的最后添加以下语句来保存这两张图:
```python
fig.savefig('heatmap.png')
sns_plot = sns.pairplot(data,hue='folder')
sns_plot.savefig('pairplot.png')
```
这将会把热力图保存为 `heatmap.png`,把散点图矩阵保存为 `pairplot.png`,并将它们存储在当前工作目录下。请确保你有当前工作目录的写入权限。
def plot_rate( rate_his, rolling_intv = 50, ylabel='标准化计算速率',ax=None): import matplotlib.pyplot as plt import pandas as pd import matplotlib as mpl rate_array = np.asarray(rate_his) # 将一个 Python 列表 rate_his 转换为 NumPy 数组 rate_array df = pd.DataFrame(rate_his) # 创建了一个名为df的Pandas DataFrame对象,将rata_his数据进行索引拆分过滤排序 if ax is None: fig, ax = plt.subplots(figsize=(15, 8)) mpl.style.use('seaborn') #设置matplotlib 库的绘图风格为 seaborn 风格 fig, ax = plt.subplots(figsize=(15,8))# 使用 Matplotlib 库创建一个带有指定大小的子图对象,宽为15,高为8 plt.plot(np.arange(len(rate_array))+1, np.hstack(df.rolling(rolling_intv, min_periods=1).mean().values), 'b') #使用plt.plot函数将生成的x轴和y轴坐标绘制成折线图,并且'b' 表示蓝色的线条。 plt.fill_between(np.arange(len(rate_array))+1, np.hstack(df.rolling(rolling_intv, min_periods=1).min()[0].values), np.hstack(df.rolling(rolling_intv, min_periods=1).max()[0].values), color = 'b', alpha = 0.2) #将这两个曲线之间的区域填充成颜色为蓝色、透明度为0.2的矩形 plt.ylabel(ylabel)# 设置纵轴标签 plt.xlabel('Time Frames')#设置横轴标签 plt.show(), plot_rate(Q.sum(axis=1)/N, 100, 'Average Data Queue') plot_rate(energy.sum(axis=1)/N, 100, 'Average Energy Consumption'),将多个函数绘制于横坐标相同的同一张图
可以通过将多个函数的数据合并成一个 NumPy 数组,然后在同一个子图对象上使用 plt.plot() 函数来绘制多条线路。下面是一个示例代码,其中包括两个函数 plot_rate() 的调用,用于在同一张图上绘制两条线路:
``` python
import numpy as np
import matplotlib.pyplot as plt
def plot_rate(rate_his, rolling_intv=50, ylabel='标准化计算速率', ax=None):
import pandas as pd
import matplotlib as mpl
rate_array = np.asarray(rate_his)
df = pd.DataFrame(rate_his)
if ax is None:
fig, ax = plt.subplots(figsize=(15, 8))
mpl.style.use('seaborn')
ax.plot(np.arange(len(rate_array))+1, np.hstack(df.rolling(rolling_intv, min_periods=1).mean().values), 'b')
ax.fill_between(np.arange(len(rate_array))+1, np.hstack(df.rolling(rolling_intv, min_periods=1).min()[0].values), np.hstack(df.rolling(rolling_intv, min_periods=1).max()[0].values), color='b', alpha=0.2)
ax.set_ylabel(ylabel)
ax.set_xlabel('Time Frames')
# Generate some sample data
N = 1000
Q = np.random.normal(0.0, 1.0, (N, 10))
energy = np.random.normal(10.0, 1.0, (N, 10))
# Create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(15, 10))
# Plot the data queue rate on the first subplot
plot_rate(Q.sum(axis=1)/N, 100, 'Average Data Queue', ax=ax1)
# Plot the energy consumption rate on the second subplot
plot_rate(energy.sum(axis=1)/N, 100, 'Average Energy Consumption', ax=ax2)
# Show the plot
plt.show()
```
这段代码将生成两个包含随机数据的 NumPy 数组 Q 和 energy。我们使用这些数组中的数据来调用 plot_rate() 函数,将数据队列速率和能量消耗速率绘制在同一张图上的两个子图中。在这个示例中,我们使用了 plt.subplots() 函数来创建一个包含两个子图的图形,然后在每个子图上调用 plot_rate() 函数来绘制数据。
阅读全文