python左上角设置图例,字体大小为15
时间: 2024-03-27 20:38:03 浏览: 105
好的,以下是一份Python代码,可以在左上角为图形添加一个图例,并将字体大小设置为15:
```python
import matplotlib.pyplot as plt
# 定义月份和销售额数据
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [20, 28, 25, 30, 35, 27]
# 绘制柱形图
plt.bar(months, sales, color='c', label='Sales')
# 添加标题和标签
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales (in 10,000 RMB)')
# 添加图例
plt.legend(fontsize=15, loc='upper left')
# 显示图形
plt.show()
```
在代码中,我们使用 `label` 参数为柱形图添加标签,然后使用 `legend` 函数为图形添加图例,其中 `fontsize` 参数设置字体大小为15,`loc` 参数设置图例的位置为左上角。
你可以根据自己的需要进行修改,但需要保证 `label` 参数和 `legend` 函数的 `label` 参数一致。同时,如果需要设置其他位置的图例,可以将 `loc` 参数修改为相应的位置代码(比如右上角为 `upper right`)。
相关问题
plt.XX #绘制不同月份的销售额(万元)柱形图,其中参数color = 'c' plt.XX#左上角设置图例,字体大小为15 plt.XX #使用twinx() 添加次坐标轴 plt.XX#绘制不同月份同比增长率折线图,红色,线宽为3, plt.XX#右上角设置图例,字体大小为15
以下是一个综合示例,演示如何绘制不同月份的销售额柱形图和同比增长率折线图,并添加图例和次坐标轴:
```python
import matplotlib.pyplot as plt
# 不同月份的销售额(万元)
sales = [100, 120, 140, 130, 110, 90, 80]
# 不同月份的同比增长率
growth_rate = [0.2, 0.3, 0.4, 0.1, -0.2, -0.1, -0.2]
# 创建一个子图
fig, ax1 = plt.subplots()
# 绘制柱形图
ax1.bar(range(len(sales)), sales, color='c', label='Sales')
ax1.set_xlabel('Month')
ax1.set_ylabel('Sales (10,000 Yuan)', color='c')
ax1.tick_params('y', colors='c')
# 添加图例
ax1.legend(loc='upper left', fontsize=15)
# 创建次坐标轴
ax2 = ax1.twinx()
# 绘制折线图
ax2.plot(range(len(growth_rate)), growth_rate, 'r-', linewidth=3, label='Growth Rate')
ax2.set_ylabel('Growth Rate', color='r')
ax2.tick_params('y', colors='r')
# 添加图例
ax2.legend(loc='upper right', fontsize=15)
# 显示图表
plt.show()
```
在这个例子中,我们首先定义了不同月份的销售额和同比增长率。然后,我们使用plt.subplots()函数创建了一个包含一个子图的图表。接下来,我们使用bar()函数在ax1上绘制了一个柱形图,并使用set_xlabel()、set_ylabel()和tick_params()函数设置了x轴、y轴和刻度的样式。同时,我们在ax1上添加了一个图例。为了绘制同比增长率折线图,我们使用twinx()函数创建了一个次坐标轴ax2,并在ax2上绘制了一个折线图。我们同样使用set_ylabel()、tick_params()和legend()函数设置了ax2的样式和图例。
最后,我们使用show()函数显示了图表。
运行这段代码后,会生成一个包含柱形图和折线图的图表,其中,左侧y轴对应销售额柱形图,右侧y轴对应同比增长率折线图。同时,图例分别位于左上角和右上角,字体大小均为15。
python的plot设置图例
### 如何在Python Matplotlib Plot中设置图例位置和样式
当使用 `matplotlib` 绘制图形并希望自定义图例外观及其位置时,可以利用多种参数来调整这些属性。下面展示了具体方法。
#### 设置图例位置
通过传递不同的字符串给 `loc` 参数可改变图例放置的位置。例如:
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 10)
y = x + 2
yy = 2 * x + 1
fig = plt.figure()
ax = plt.gca()
line_a = ax.plot(x, y, label='a', c='coral')
line_b = ax.plot(x, yy, label='b', c='yellow')
plt.legend(loc="upper left") # 将图例置于左上角[^2]
plt.show()
```
如果想要更精确控制图例的位置,则可以通过指定坐标的方式来进行定位:
```python
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') # 把图例放到图框之外的左上方[^3]
```
这里 `bbox_to_anchor` 定义了相对于当前轴对象(axes object)外部的一个锚点;而 `loc` 则指定了该锚点对应于图例矩形框中的哪个角落或中心部分。
#### 自定义图例外观
除了位置外,还可以修改图例边框的颜色、透明度等外观特性。这可通过向 `legend()` 函数传入额外的关键字参数完成:
```python
plt.legend(frameon=False) # 不显示图例背景框[^4]
```
对于更加复杂的定制需求,比如更改字体大小、线条宽度等,也可以相应地添加更多关键字参数到 `legend()` 调用之中。
阅读全文
相关推荐
















