python画散点图图例
时间: 2023-08-31 14:09:20 浏览: 49
可以使用Matplotlib库中的scatter函数来画散点图,并且使用legend函数来添加图例。下面是一个示例代码:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 8, 12, 9, 11]
labels = ['point 1', 'point 2', 'point 3', 'point 4', 'point 5']
plt.scatter(x, y, label='data points')
for i, label in enumerate(labels):
plt.annotate(label, (x[i], y[i]))
plt.legend()
plt.show()
```
在上面的代码中,x和y分别是散点的横坐标和纵坐标,labels是每个散点点的标签。scatter函数用来画散点图,label参数用来设置图例的标签。在for循环中,使用annotate函数给每个散点添加标签。最后使用legend函数添加图例,然后调用show函数展示图像。
相关问题
python调整折线图图例位置
您可以使用matplotlib库的legend()函数来调整折线图的图例位置,例如:
```python
import matplotlib.pyplot as plt
# 绘制折线图
x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]
plt.plot(x, y)
# 设置图例位置
plt.legend(loc='upper right')
# 显示图形
plt.show()
```
这里,`loc='upper right'`表示将图例放置在右上角。您可以选择其他位置,如'upper left','lower right'等。
python画折线图如何使图例不覆盖数据
如果在绘制折线图时,图例覆盖了数据,可以通过调整图例的位置或者修改图例的大小来解决。下面是两种解决方法:
1. 调整图例的位置
可以使用`plt.legend()`函数中的`loc`参数来调整图例的位置,常用的位置参数有:
- `'best'`: 自动选择最佳位置
- `'upper right'`: 右上角
- `'upper left'`: 左上角
- `'lower right'`: 右下角
- `'lower left'`: 左下角
例如,将图例放在右上角可以这样写:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, label='Line 1')
plt.legend(loc='upper right')
plt.show()
```
2. 修改图例的大小
可以使用`plt.legend()`函数中的`fontsize`参数来修改图例的字体大小,例如:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, label='Line 1')
plt.legend(fontsize=12)
plt.show()
```
这样就可以将图例的字体大小调整为12。