python 画多个集合散点图
时间: 2024-01-01 18:02:32 浏览: 120
Python可以使用matplotlib库中的scatter函数来绘制多个集合的散点图。以下是一个简单的例子来说明如何使用Python绘制多个集合的散点图:
```python
import matplotlib.pyplot as plt
# 创建第一个集合的数据
x1 = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
# 创建第二个集合的数据
x2 = [1, 3, 5, 7, 9]
y2 = [1, 3, 5, 7, 9]
# 创建第三个集合的数据
x3 = [2, 4, 6, 8, 10]
y3 = [10, 8, 6, 4, 2]
# 绘制散点图
plt.scatter(x1, y1, label='集合1')
plt.scatter(x2, y2, label='集合2')
plt.scatter(x3, y3, label='集合3')
# 添加图例
plt.legend()
# 设置横纵坐标轴标签
plt.xlabel('x轴')
plt.ylabel('y轴')
# 设置图标题
plt.title('多个集合的散点图')
# 显示图形
plt.show()
```
上述代码会创建3个集合的数据,并使用scatter函数分别绘制了这3个集合的散点图。可以根据实际需求修改x、y的值,并为每个集合指定一个标签,以便在图例中显示。最后,通过设置坐标轴标签和图标题,然后调用`plt.show()`来显示图形。
相关问题
python画出平滑折线图,数据标注
### 使用 Python Matplotlib 和 Seaborn 绘制带数据标签的平滑曲线图
为了绘制带有数据标注的平滑折线图,可以利用 `Matplotlib` 或者更高级别的接口 `Seaborn` 来完成此操作。下面展示两种方法来实现这一目标。
#### 方法一:使用 Matplotlib 实现
通过调整参数并应用样条插值技术可以使线条更加光滑。这里提供了一个简单的例子:
```python
import numpy as np
from scipy.interpolate import make_interp_spline
import matplotlib.pyplot as plt
# 创建一些测试数据点
x = np.array([1, 2, 3, 4, 5])
y = np.array([1, 4, 9, 16, 25])
# 构造三次B样条对象
X_Y_Spline = make_interp_spline(x, y)
# 返回更多间隔均匀的新坐标以便于绘制成平滑图形
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
plt.figure(figsize=(8, 6))
plt.plot(X_, Y_)
for i,j in zip(x,y):
plt.text(i, j+0.5,'({},{})'.format(i,int(j)), ha='center', va='bottom')
plt.title('Smooth Line Chart with Data Labels')
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
plt.grid(True)
plt.show()
```
这段代码首先定义了一些离散的数据点作为输入,接着采用 B 样条插值算法使得这些点之间连接起来形成一条较为流畅自然过渡的路径[^1]。
#### 方法二:基于 Seaborn 的 KDE 图形增强版
如果希望得到既美观又专业的效果,则推荐尝试 seaborn 库里的核密度估计 (KDE) 功能,在此基础上添加自定义标记以显示具体数值位置:
```python
import pandas as pd
import seaborn as sns; sns.set_theme(style="whitegrid")
tips = sns.load_dataset("tips")
def plot_kde_with_labels(dataframe, column_name):
fig, ax = plt.subplots()
# Draw the density plot using seaborn's histplot function.
sns.kdeplot(
data=dataframe,
x=column_name,
fill=True,
alpha=.4,
linewidth=2,
color="#ff7f0e",
ax=ax
)
# Annotate each point on original dataset.
for idx, row in dataframe.iterrows():
ax.annotate(f'({row[column_name]:.1f}, {max(sns.kdeplot(data=row[[column_name]], cumulative=False).get_lines()[0].get_ydata()):.3f})',
xy=(row[column_name], max(sns.kdeplot(data=row[[column_name]], cumulative=False).get_lines()[0].get_ydata())),
textcoords="offset points", # how to position the text
xytext=(-10,-10), # distance from text to points (x,y)
ha='right'
)
plt.title(f'Smooth Curve of "{column_name}" Distribution With Annotations')
plt.tight_layout()
plt.show()
plot_kde_with_labels(tips, 'total_bill')
```
上述脚本加载了内置的小费 (`tips`) 数据集,并针对总账单金额列 ('total_bill') 执行了 KDE 曲线拟合过程;与此同时,遍历原始记录集合中的每一个实例项,为其附加相应的文本说明框[^3]。
python画折线图编区间
### 绘制带置信区间的折线图
为了实现这一目标,可以利用 `matplotlib` 和 `seaborn` 库中的功能来创建带有置信区间的折线图。下面展示了一个具体的例子,该例子通过模拟的数据集展示了如何绘制这样的图表。
#### 使用 Seaborn 的 lineplot 函数绘制带置信区间的折线图
Seaborn 提供了内置的支持用于自动计算并显示估计值周围的不确定性区域,这通常表现为围绕线条的阴影部分表示标准误差或其他形式的置信区间[^1]。
```python
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# 设置中文字体和解决符号显示问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False # 解决负号'-'显示为方块的问题[^2]
# 创建示例数据
np.random.seed(0)
data = {
'x': range(10),
'y': np.random.randn(10).cumsum() + 4,
}
df = pd.DataFrame(data)
# 添加一些噪声以形成多个样本点
noisy_data = []
for i in df.index:
noisy_y_values = np.random.normal(loc=df.loc[i, "y"], scale=0.5, size=100)
for value in noisy_y_values:
noisy_data.append([df.loc[i, "x"], value])
noisy_df = pd.DataFrame(noisy_data, columns=['x', 'y'])
# 绘制带置信区间的折线图
sns.lineplot(x='x', y='y', data=noisy_df, ci="sd") # 使用标准差作为置信区间范围
plt.title('带置信区间的折线图')
plt.show()
```
这段代码首先设置了中文环境以便于图形上的文本正常显示。接着构建了一组基础数据,并基于这些数据制造了一些具有随机波动的新观测值集合。最后调用了 `lineplot()` 方法,在其中指定了参数 `ci="sd"` 来指示希望用标准偏差定义置信水平下的不确定度区域。
阅读全文
相关推荐
















