Home > Software design >  matplotlib stacked bar chart with zero centerd
matplotlib stacked bar chart with zero centerd

Time:11-01

I have a dataset like below.

T/F Value category
T 1 A
F 3 B
T 5 C
F 7 A
T 8 B
... ... ...

so, I want to draw a bar chart like below. same categoy has same position

same category has same position, zero centered bar and number of F is bar below the horizontal line, T is upper bar. enter image description here

How can I make this chart with matplotlib.pyplot? or other library

I need example.

CodePudding user response:

One approach involves making the False values negative, and then creating a Seaborn barplot with T/F as hue. You might want to make a copy of the data if you can't change the original.

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

data = pd.DataFrame({'T/F': ['T', 'F', 'T', 'F', 'T'],
                     'Value': [1, 3, 5, 7, 8],
                     'category': ['A', 'B', 'C', 'A', 'B']})
data['Value'] = np.where(data['T/F'] == 'T', data['Value'], -data['Value'])
ax = sns.barplot(data=data, x='category', y='Value', hue='T/F', dodge=False, palette='turbo')
ax.axhline(0, lw=2, color='black')
plt.tight_layout()
plt.show()

sns.barplot joining positives and negatives

  • Related