python - 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:
For reference this is the type of graph I am trying to achieve.
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:
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)
解决方案
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
推荐阅读
- swift - 在 Swift 中,计算 2 个值的总和两次或计算一次并将结果存储在变量中会更快吗?
- python-3.x - Python tkinter 窗口调用导致系统重启
- ios - 如何删除 CKRecord 中的键和对象?
- swift - 有没有办法搜索从另一个视图控制器的 json 文件中获取的内容?
- php - PHP ODBC_connect 与现有的 ODBC 驱动程序
- php - 'Warning: require(C:\wamp64\www\laravel\bootstrap/../vendor/autoload.php) 无法打开流的原因是什么:
- javascript - Javascript 在创建值为对象的属性时使用的命名样式
- c# - 如何从另一个类调用 ICommand 属性
- ocaml - 如何将文本与 OCaml 中的 Vg 库右对齐?
- delphi - tdxSpreadSheet,如何在代码中创建的单元格中格式化浮点数,例如“123.450”