Python plot data as bar-candle-like chart

Viewed 42

I have a dataset with following structue:

[Title,Value_A,Value_B]

Some real world examples are:

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

I want a bar-like chart like this sketch:

Example Image

I want to use matplotlib.pyplot lib, tried a lot but just need a hint. Also,i am open for other libraries.

Edit1: Sorry i was not precise enough. Data is stored in 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()

This is what i got as simple start. My Problem is that i dont know how to feed the y axes with 2 values which are present as a bar/candle.

2 Answers

Maybe this one is what you need:

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()

You can use 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()

plot_result


Alternatively as @LuisAlejandro suggested, you can use ax.violinplot, but you have to extract the values from the dataframe first:

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()

violin-plot

Related