plt.scatter(data['MEDV'], data['B'], alpha=0.5) plt.xlabel('MEDV') plt.ylabel('B') plt.title('Scatter plot of MEDV and B') plt.show() plt.scatter(data['MEDV'], data['LSTAT'], alpha=0.5) plt.xlabel('MEDV') plt.ylabel('LSTAT') plt.title('Scatter plot of MEDV and LSTAT') plt.show()
时间: 2023-09-02 13:13:16 浏览: 43
这是一个使用matplotlib库在Python中绘制散点图的代码示例。第一段代码绘制了'MEDV'和'B'之间的散点图,第二段代码绘制了'MEDV'和'LSTAT'之间的散点图。在绘制散点图时,'MEDV'被设置为横坐标,而'B'和'LSTAT'被设置为纵坐标。通过alpha参数设置透明度,使得散点图更易于观察。xlabel和ylabel函数用于设置横纵坐标的标签,title函数用于设置图表的标题。最后,使用show函数显示图表。
相关问题
fig, ax1 = plt.subplots() color = 'tab:red' ax1.set_xlabel('Index') ax1.set_ylabel('MEDV', color=color) ax1.plot(data['MEDV'], color=color) ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() color = 'tab:blue' ax2.set_ylabel('CRIM', color=color) ax2.plot(data['CRIM'], color=color) ax2.tick_params(axis='y', labelcolor=color) fig.tight_layout() plt.title('Line plot of CRIM and MEDV') plt.show() # 绘制CRIM和MEDV的散点图 plt.scatter(data.index, data['CRIM'], s=5) plt.scatter(data.index, data['MEDV'], s=5) plt.legend() plt.ylabel('Value') plt.xlabel('Index') plt.show()
这是一个使用matplotlib库在Python中绘制线图和散点图的代码示例。第一段代码绘制了'MEDV'和'CRIM'之间的线图。通过调用subplots函数创建一个包含两个子图的图表,其中ax1是左侧子图,ax2是右侧子图。在左侧子图中,'MEDV'被设置为纵坐标,'CRIM'被设置为右侧子图的纵坐标。在右侧子图中,'CRIM'被设置为纵坐标。通过设置tick_params函数中的labelcolor参数,使得左右两个子图的刻度标签颜色不同。最后,使用tight_layout函数调整图表布局,并使用show函数显示图表。
第二段代码绘制了'MEDV'和'CRIM'之间的散点图。使用scatter函数绘制散点图,其中x轴被设置为数据的索引,y轴被设置为'MEDV'和'CRIM'。使用legend函数添加图例,使得可以区分'MEDV'和'CRIM'的散点图。最后,使用ylabel和xlabel函数设置横纵坐标的标签,并使用show函数显示图表。
import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt # 读取数据 data = pd.read_csv('D:/pythonProject/venv/BostonHousing2.csv') # 提取前13个指标的数据 X = data.iloc[:, 5:18].values # 数据标准化 scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 主成分分析 pca = PCA() X_pca = pca.fit_transform(X_scaled) # 特征值和特征向量 eigenvalues = pca.explained_variance_ eigenvectors = pca.components_.T # 碎石图 variance_explained = np.cumsum(eigenvalues / np.sum(eigenvalues)) plt.plot(range(6, 19), variance_explained, marker='o') plt.xlabel('Number of Components') plt.ylabel('Cumulative Proportion of Variance Explained') plt.title('Scree Plot') plt.show() # 选择主成分个数 n_components = np.sum(variance_explained <= 0.95) + 1 # 前2个主成分的载荷图 loadings = pd.DataFrame(eigenvectors[:, 0:2], columns=['PC1', 'PC2'], index=data.columns[0:13]) plt.figure(figsize=(10, 6)) plt.scatter(loadings['PC1'], loadings['PC2'], alpha=0.7) for i, feature in enumerate(loadings.index): plt.text(loadings['PC1'][i], loadings['PC2'][i], feature) plt.xlabel('PC1') plt.ylabel('PC2') plt.title('Loading Plot') plt.grid() plt.show() # 主成分得分图 scores = pd.DataFrame(X_pca[:, 0:n_components], columns=['PC{}'.format(i+1) for i in range(n_components)]) plt.figure(figsize=(10, 6)) plt.scatter(scores['PC1'], scores['PC2'], alpha=0.7) for i, label in enumerate(data['MEDV']): plt.text(scores['PC1'][i], scores['PC2'][i], label) plt.xlabel('PC1') plt.ylabel('PC2') plt.title('Scores Plot') plt.grid() plt.show() # 综合评估和排序 data['PC1_score'] = X_pca[:, 0] sorted_data = data.sort_values(by='PC1_score') # 主成分回归模型 from sklearn.linear_model import LinearRegression Y = data['MEDV'].values.reshape(-1, 1) X_pca_regression = X_pca[:, 0].reshape(-1, 1) regression_model = LinearRegression() regression_model.fit(X_pca_regression, Y) # 回归方程 intercept = regression_model.intercept_[0] slope = regression_model.coef_[0][0] equation = "MEDV = {:.2f} + {:.2f} * PC1".format(intercept, slope) print("Regression Equation:", equation) # 最小二乘估计结果 from statsmodels.api import OLS X_const = np.concatenate((np.ones((506, 1)), X_pca_regression), axis=1) ols_model = OLS(Y, X_const).fit() print("OLS Regression Summary:") print(ols_model.summary())
这段代码是用 Python 对波士顿房价数据进行主成分分析(PCA)。该代码读取了一个名为 "BostonHousing2.csv" 的数据文件,并将前 13 个指标的数据提取出来,进行了数据标准化和主成分分析。其中,碎石图展示了不同主成分个数下的累计方差贡献率,用于选择主成分个数;载荷图展示了前两个主成分对原始数据各个指标的影响程度;得分图展示了每个房价样本在前两个主成分上的得分情况,用于评估房价的相对位置。最后,该代码还进行了主成分回归模型和最小二乘估计结果的计算和展示。