Skip to main content
 首页 » 编程设计

python之Pandas中水平条形图的修改

2024年10月17日9linjiqin

我已经使用 Pandas plot 功能制作了一个plot,但希望能帮助您使用以下元素完成它(如所需输出图图像所示):

  1. x 轴上 0 处的垂直线。
  2. x 轴上 10 点增量。
  3. 我希望 OpenToLast 条形数据更加突出,所以如果可能的话,是否希望将其他堆叠的条形淡化到背景中?

数据:

请查看 DataFrame.to_dict() 输出 here .

这就是我获取现有plot的方式:

auction[['OpenToLast','OpenToMaxHigh','OpenToMaxLow']].head(20).plot(kind='barh', 
                        figsize=(7,10), 
                        fontsize=10, 
                        colormap ='winter',                                         
                        stacked = True,                                 
                        legend = True) 

当前剧情:

期望的输出:

请您参考如下方法:

尝试以下操作:

事实证明,最棘手的部分是着色,但绘制线条和更新刻度线相对简单(请参阅代码末尾)

import numpy as np 
 
# get the RGBA values from your chosen colormap ('winter') 
winter = matplotlib.cm.winter  
winter = winter(range(winter.N)) 
 
# select N elements from winter depending on the number of columns in your 
# dataframe (make sure they are spaced evenly from the colormap so they are as  
# distinct as possible) 
winter = winter[np.linspace(0,len(winter)-1,auction.shape[1],dtype=int)] 
 
# set the alpha value for the two rightmost columns  
winter[1:,3] = 0.2   # 0.2 is a suggestion but feel free to play around with this value 
 
new_winter = matplotlib.colors.ListedColormap(winter) # convert array back to a colormap    
 
# plot with the new colormap 
the_plot = auction[['OpenToLast','OpenToMaxHigh','OpenToMaxLow']].head(20).plot(kind='barh', 
                        figsize=(7,10), 
                        fontsize=10, 
                        colormap = new_winter,                                         
                        stacked = True,                                 
                        legend = True) 
 
the_plot.axvline(0,0,1) # vertical line at 0 on the x axis 
start,end = the_plot.get_xlim() # find current span of the x axis 
the_plot.xaxis.set_ticks(np.arange(start,end,10)) # reset the ticks on the x axis with increments of 10