matplotlib 将数据绘制为条形蜡烛图

06odsfpq  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(132)

我有一个具有以下结构的数据集:

[Title,Value_A,Value_B]

一些真实的世界的例子是:

[A,0.1,0.3]
[B,0.5,0.6]
[I,1,0.6]
[R,0.6,0.7]

我想要一个像这样的条形图:
Example Image
我想使用matplotlib。pyplot lib,尝试了很多,但只是需要一个提示。此外,我对其他库开放。
Edit 1:对不起,我不够精确。数据存储在Pandas DataFrame中

import matplotlib.pyplot as plt
import pandas as pd

df=pd.DataFrame()
df["title"] = ("A","B","C","D")
df["value_1"] = (0.1,0.5,1,0.6)
df["value_2"] = (0.3,0.6,0.6,0.7)
df.plot(x="title", y="value_1", kind="bar",stacked=True)
plt.show()

这是我得到的简单的开始。我的问题是,我不知道如何饲料的y轴与2个值,这是目前作为一个酒吧/蜡烛。

z2acfund

z2acfund1#

也许这就是你需要的:

import matplotlib.pyplot as plt

collectn_1 = [0.1,0.3]
collectn_2 = [0.5,0.6]
collectn_3 = [0.6,1]
collectn_4 = [0.6,0.7]

## combine these different collections into a list
data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]

# Create a figure instance
fig = plt.figure()

# Create an axes instance
ax = fig.add_axes([0,0,1,1])

# Create the boxplot
bp = ax.violinplot(data_to_plot)
plt.show()
cnwbcb6i

cnwbcb6i2#

可以使用plt.bar

fig, ax = plt.subplots()

ax.bar(x=df['title'], 
       bottom=df['value_1'], 
       height=df['value_2'] - df['value_1'])

ax.set_ylim(bottom=0, top=1.2)
new_yticks = list(set(df['value_1']).union(df['value_2']))
plt.yticks(new_yticks)
plt.show()

或者如@LuisAlejandro所建议的,您可以使用ax.violinplot,但您必须首先从嵌套框中提取值:

vals = list(df[['value_1', 'value_2']].T.to_dict('list').values())
# [[0.1, 0.3], [0.5, 0.6], [1.0, 0.6], [0.6, 0.7]]

fig, ax = plt.subplots()

ax.violinplot(vals)

ax.set_ylim(bottom=0, top=1.2)
plt.yticks(new_yticks)
plt.show()

相关问题