簡體   English   中英

修改 Pandas 中的水平條形圖

[英]Modification of horizontal bar plot in Pandas

我已經使用 Pandas plot功能組合了一個plot ,但希望能幫助您使用以下元素完成它(如所需的輸出繪圖圖像所示):

  1. x 軸上 0 處的垂直線。
  2. x 軸上 10 點增量。
  3. 我希望OpenToLast條形數據更加突出,因此如果可能的話,是否希望將其他堆疊的條形淡入背景?

數據:

在此處查看DataFrame.to_dict()輸出。

這就是我獲得現有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

在此處輸入圖片說明

我沒有意識到我可以直接通過 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')

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM