大Pandas单杠图的改进

2024-05-23 15:56:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经使用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)

当前绘图:

enter image description here

期望输出:

enter image description here


Tags: to数据图像功能true元素dataframepandas
2条回答

我没有意识到我可以在matplotlibapi中直接使用Pandasplot命令。现在,我复制了上面的代码,并进行了修改,以便在Matplotlib中添加其他元素。在

如果有人知道怎么做的话,最好在横条上加一个渐变,但是我会把这个问题标记为回答:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

cols = ['OpenToLast','OpenToMaxHigh','OpenToMaxLow']
colors = {'OpenToLast':'b', 'OpenToMaxHigh' : '#b885ea', 'OpenToMaxLow': '#8587ea'}

axnum = auction[cols].head(20).plot(kind='barh',
                        figsize=(7,10),
                        fontsize=10,
                        color=[colors[i] for i in cols],                                       
                        stacked = True,                                
                        legend = True)

axnum.xaxis.set_major_locator(ticker.MultipleLocator(10))
plt.axvline(0, color='b')

enter image description here

尝试以下操作:

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

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

enter image description here

相关问题 更多 >