无法使用python/matlibplot为所有标记的4行生成图例

2024-05-14 12:44:52 发布

您现在位置:Python中文网/ 问答频道 /正文

想要布林带(R)的标签('上带','滚动平均','下带')显示在图例中。但是legend只对每一行应用相同的标签,第一(唯一)列“IBM”的标签是pandas。你知道吗

# Plot price values, rolling mean and Bollinger Bands (R)
ax = prices['IBM'].plot(title="Bollinger Bands")
rm_sym.plot(label='Rolling mean', ax=ax)
upper_band.plot(label='upper band', c='r', ax=ax)
lower_band.plot(label='lower band', c='r', ax=ax)
#
# Add axis labels and legend
ax.set_xlabel("Date")
ax.set_ylabel("Adjusted Closing Price")
ax.legend(loc='upper left')
plt.show()

我知道这段代码可能表示对matlibplot的工作原理缺乏基本的了解,因此特别欢迎解释。你知道吗


Tags: andbandplot标签axmeanupperlower
1条回答
网友
1楼 · 发布于 2024-05-14 12:44:52

问题很可能是无论upper_bandlower_band是什么,它们都没有标记。你知道吗

一种方法是通过将它们作为列放入数据帧来标记它们。这将允许直接绘制dataframe列。你知道吗

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

y  =np.random.rand(4)
yupper = y+0.2
ylower = y-0.2

df = pd.DataFrame({"price" : y, "upper": yupper, "lower": ylower})

fig, ax = plt.subplots()
df["price"].plot(label='Rolling mean', ax=ax)
df["upper"].plot(label='upper band', c='r', ax=ax)
df["lower"].plot(label='lower band', c='r', ax=ax)

ax.legend(loc='upper left')
plt.show()

否则也可以直接绘制数据。你知道吗

import matplotlib.pyplot as plt
import numpy as np

y  =np.random.rand(4)
yupper = y+0.2
ylower = y-0.2

fig, ax = plt.subplots()
ax.plot(y,      label='Rolling mean')
ax.plot(yupper, label='upper band', c='r')
ax.plot(ylower, label='lower band', c='r')

ax.legend(loc='upper left')
plt.show()

在这两种情况下,您将得到一个带有标签的图例。如果这还不够,我建议您阅读Matplotlib Legend Guide,它还告诉您如何手动向图例添加标签。你知道吗

相关问题 更多 >

    热门问题