【问题标题】:How to plot bars such that for value less than a threshold value are in an opposite direction than the ones greater?如何绘制条形图,使得小于阈值的值与更大的值相反?
【发布时间】:2020-07-16 11:38:58
【问题描述】:

这是有问题的图表:

作为参考,这是我想要实现的图表类型。

在上面的参考图中,下面的条形对应于负值,因此方向相反。因此,为了绘图目的,我尝试将所有值设置为相应的负值。但是,作为输出,我得到了所有相同长度的条:

这是我用来在 Seaborn 中绘制图表的代码:

import unicodedata # to print pound sign

# Set the plot style and colour palette to use (remember dodgy spelling if you're from the UK!)
sns.set(style='whitegrid')
sns.set_color_codes('muted')
sns.set(font_scale=2)

 
# Initialize the matplotlib figure (f) and axes (ax), and set width and height of the plot
f, ax = plt.subplots(figsize=(12, 10))
# ax.set_xlim(-90,103)
# ax.set_xticks(range(9,103))
 
# Create the plot, choosing the variables for each axis, the data source and the colour (b = blue)
# show_values_on_bars(ax, h_v="v", space=0.4)
sns_t= sns.barplot(x='Final Team Value', y='Name', 
                   data=final_bank_value,
                   palette='Spectral')
for p in ax.patches:
    width = p.get_width()
    ax.text(width -0.7  ,
            p.get_y()+p.get_height()/2. + 0.2,
            '{}{:1.2f}'.format(unicodedata.lookup("Pound Sign"),width), ha="left")

# Rename the axes, setting y axis label to be blank
ax.set(ylabel='', xlabel='Final Value of Team')
 
# Remove the borders from the plot
sns.despine(left=True, bottom=True)

【问题讨论】:

    标签: python matplotlib data-visualization seaborn


    【解决方案1】:

    为了在某个阈值创建负数据,我们使用以下方法运行代码,根据该数据绘制图表并附上绘制的图表。

    import pandas as pd
    import unicodedata
    
    final_bank_value = pd.DataFrame({'Name':['nameA','nameB','nameC','nameD'],'Final Team Value':[250,289,55,15]}, index=[0,1,2,3])
    final_bank_value['Final Team Value'] = final_bank_value['Final Team Value'].apply(lambda x: x * -1 if x <= 100 else x)
    final_bank_value
    
    
    Name    Final Team Value
    0   nameA   250
    1   nameB   289
    2   nameC   -55
    3   nameD   -15
    

    【讨论】:

    • 我像你一样用负值绘制了图表。但是,在我的情况下,尽管条形图改变了方向,但当我用负值绘制它时,我的所有条形图都具有相同的长度。我已在原始问题中附上了结果图。
    • 不只是贴出的图表中的三个负值是相近的数字,所以它们看起来一样吗?尝试更改这些值怎么样?
    • 是的。这就说得通了。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2022-01-07
    • 2019-06-03
    • 2021-09-26
    • 1970-01-01
    相关资源
    最近更新 更多