matplotlib boston
时间: 2023-11-08 09:00:25 浏览: 36
Matplotlib是Python中一个用于绘制图表和可视化数据的强大工具。您可以使用Matplotlib的plot()函数绘制一系列点,并用线连接它们。您还可以通过设置不同的参数,如颜色、线型、标记等,来定制您的图表。下面是一个示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, np.pi)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.plot(x, y_sin, 'go--', linewidth=2, markersize=12)
plt.plot(x, y_cos, color='red', marker=' ', linestyle='dashed')
plt.show()
```
在这个示例中,我们使用了`np.linspace()`函数生成了一个从0到π的等间隔的数组作为x轴数据,然后使用`np.sin()`和`np.cos()`函数生成了对应的y轴数据。之后,我们通过`plot()`函数分别绘制了sin(x)和cos(x)的图表,并设置了不同的参数来调整线条和标记的样式。最后,通过`show()`函数显示了图表。
相关问题
matplotlib绘图代码示例
以下是三个关于Matplotlib绘图的代码示例:
示例1:绘制线形图
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2, 2, 100)
y = x**2
z = np.sqrt(4-x**2)
plt.plot(x, y, label='$y=x^2$', color='red', linewidth=2)
plt.plot(x, z, 'b--', label='$x^2 + y^2 = 4$')
plt.plot(x, -z, 'y--', label='$x^2 + y^2 = 4$')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('线形图')
plt.xlim(-5, 5)
plt.ylim(-5, 5)
plt.legend()
plt.grid()
plt.savefig('pyplot.png', format='png', dpi=500)
plt.show()
```
示例2:绘制带箭头的坐标轴
```python
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist
import numpy as np
fig = plt.figure(figsize=(6, 6))
ax = axisartist.Subplot(fig, 111)
fig.add_axes(ax)
ax.axis[:].set_visible(False)
ax.axis['x'] = ax.new_floating_axis(0, 0)
ax.axis['y'] = ax.new_floating_axis(1, 0)
ax.axis['x'].set_axisline_style('-|>', size=1.0)
ax.axis['y'].set_axisline_style('-|>', size=1.0)
ax.axis['x'].set_axis_direction('top')
ax.axis['y'].set_axis_direction('right')
plt.xlim(-10, 10)
plt.ylim(-0.1, 1.2)
x = np.arange(-10, 10, 0.1)
y = 1/(1 + np.exp(-x))
plt.plot(x, y, label=r'$sigmoid=\frac{1}{1+e^{-x}}$', c='r')
plt.legend()
plt.savefig('sigmoid.png', format='png', dpi=500)
plt.show()
```
示例3:添加图例说明
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 25, 30], label='Philadelphia')
ax.plot([1, 2, 3, 4], [30, 23, 13, 4], label='Boston')
ax.scatter([1, 2, 3, 4], [20, 10, 30, 15], label='Point')
ax.set(ylabel='Temperature (deg C)', xlabel='Time', title='A tale of two cities')
ax.legend()
plt.show()
```
这些示例展示了Matplotlib绘图的不同用法,包括绘制线形图、带箭头的坐标轴和添加图例说明。你可以根据需要选择适合的示例进行使用。
boston房价预测python
要预测Boston房价,可以使用机器学习算法来实现。以下是一个使用Python实现的简单的线性回归模型:
1. 首先,导入必要的库,包括pandas,numpy,matplotlib和sklearn:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
```
2. 加载数据集,可以使用sklearn自带的Boston房价数据集:
```python
from sklearn.datasets import load_boston
boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = pd.DataFrame(boston.target, columns=['MEDV'])
```
3. 探索性数据分析,查看数据的基本信息和特征之间的关系:
```python
plt.scatter(X['RM'], y['MEDV'])
plt.xlabel('Average number of rooms per dwelling')
plt.ylabel('Median value of owner-occupied homes in $1000s')
plt.show()
```
4. 划分训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
```
5. 建立线性回归模型并训练:
```python
lin_reg = LinearRegression()
lin_reg.fit(X_train, y_train)
```
6. 预测测试集:
```python
y_pred = lin_reg.predict(X_test)
```
7. 评估模型表现:
```python
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
print('RMSE:', rmse)
```
这里只是一个简单的线性回归模型,还可以使用其他机器学习算法来预测Boston房价,如决策树、随机森林等。