首页 > 解决方案 > How to plot bars such that for value less than a threshold value are in an opposite direction than the ones greater?

问题描述

This is the graph in question:

enter image description here For reference this is the type of graph I am trying to achieve.

This is the graph in question

In the reference graph above, the bars below correspond to negative values and are hence in the opposite direction. So, I tried to set all values to their corresponding negative values for plotting purposes. But, as an output, I get all the bars of same length:

enter image description here

This is the code I used to plot the graph in 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)

标签: pythonmatplotlibdata-visualizationseaborn

解决方案


To create negative data at a certain threshold, we used the following method I've run the code to draw your graph based on that data and attached the graph drawn.

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

enter image description here


推荐阅读