Pandas

时间:2017-01-15 10:11:42

标签: python pandas matplotlib

我已经使用Pandas plot功能组合了plot,但我们非常感谢帮助完成以下元素(如所需的输出图像所示):

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

    请参阅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

2 个答案:

答案 0 :(得分:2)

尝试以下方法:

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

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

答案 1 :(得分:0)

我没有意识到我可以直接使用Matplotlib API使用Pandas plot命令。我现在已经复制了上面的代码并进行了修改,以便在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