[英]Bar chart with separate bars for positive and negative values
I have a dataframe with both positive and negative values.我有一个具有正值和负值的 dataframe。 I would like to show a bar chart that shows two bars, one bar shows the percentage of positive values and another percentage of negative values.
我想显示一个条形图,它显示两个条形图,一个条形图显示正值的百分比,另一个显示负值的百分比。
dummy = pd.DataFrame({'A' : [-4, -3, -1, 0, 1, 2, 3, 4, 5], 'B' : [-4, -3, -1, 0, 1, 2, 3, 4, 5]})
less_than_0 = dummy['A'][dummy['A'] < 0]
greater_than_0 = dummy['A'][dummy['A'] >= 0]
I am able to split the positive and negative values.我能够拆分正值和负值。 I tried this using seaborn.
我用 seaborn 试过这个。
sns.barplot(dummy['A'])
but both positive and negative are coming in single bar.但正面和负面都出现在单条中。 I tried this too
我也试过这个
sns.barplot(less_than_0)
sns.barplot(greater_than_0)
Is there any way to show 2 bars, 1 for percentage of positive values and other for percentage of negative values?有什么方法可以显示 2 个条形图,1 个代表正值的百分比,另一个代表负值的百分比?
This isn't the most elegant solution, but you can create a new DataFrame that contains two columns: labels
that contain the labels you want to display on the x-axis of the barplot, and percentages
that contain the percentages of negative and positive values.这不是最优雅的解决方案,但您可以创建一个新的 DataFrame 包含两列:包含要在条形图的 x 轴上显示的标签的
labels
,以及包含负值和正值percentages
的百分比.
Then you can pass these column names with the relevant information to sns.barplot
as the x
and y
parameters.然后,您可以将这些列名称与相关信息作为
x
和y
参数传递给sns.barplot
。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
dummy = pd.DataFrame({'A' : [-4, -3, -1, 0, 1, 2, 3, 4, 5], 'B' : [-4, -3, -1, 0, 1, 2, 3, 4, 5]})
df_percentages = pd.DataFrame({
'labels':['Less than 0', 'Greater than or equal to 0'],
'percentage':[100*x/len(dummy['A']) for x in [sum(dummy['A'] < 0), sum(dummy['A']>=0)]]
})
sns.barplot(x='labels', y='percentage', data=df_percentages)
plt.show()
You can use Series.value_counts
with normalize=True
and then plot Series
:您可以将
Series.value_counts
与normalize=True
一起使用,然后使用 plot Series
:
d = {True:'Less than 0',False:'Greater than or equal to 0'}
s = (dummy['A'] < 0).value_counts(normalize=True).rename(d)
print (s)
Greater than or equal to 0 0.666667
Less than 0 0.333333
Name: A, dtype: float64
sns.barplot(x=s.index, y=s.to_numpy())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.