2017-03-06 21 views
0

Ich habe ein Diagramm, in Python färben ich mit matplotlib mit dem folgenden Code vorgenommen haben:Wie matplotlib Graph mit Farbverlauf

def to_percent(y, position): 
    s = str(250 * y) 
    if matplotlib.rcParams['text.usetex'] is True: 
     return s + r'$\%$' 
    else: 
     return s + '%' 

distance = df['Distance'] 
perctile = np.percentile(distance, 90) # claculates 90th percentile 
bins = np.arange(0,perctile,2.5) # creates list increasing by 2.5 to 90th percentile 
plt.hist(distance, bins = bins, normed=True) 
formatter = FuncFormatter(to_percent) #changes y axis to percent 
plt.gca().yaxis.set_major_formatter(formatter) 
plt.axis([0, perctile, 0, 0.10]) #Defines the axis' by the 90th percentile and 10%Relative frequency 
plt.xlabel('Length of Trip (Km)') 
plt.title('Relative Frequency of Trip Distances') 
plt.grid(True) 
plt.show() 

enter image description here

Was wissen ich möchte ist, Es ist möglich, die Balken mit Farbverlauf statt Blockfarbe zu färben, wie in diesem Bild von Excel.

enter image description here

habe ich finden kann, um keine Informationen zu diesem Thema nicht.

+0

Statt Aufruf 'hist' Sie' numpy.histogram' verwenden könnte und Plotten mit 'bar'. Dann würde [Beispiel aus der Dokumentation] (http://matplotlib.org/examples/pylab_examples/gradient_bar.html) gelten. – wflynny

+0

Mögliches Duplikat von [Wie füllen Sie Matplotlib-Balken mit einem Farbverlauf?] (Http://stackoverflow.com/questions/38830250/how-to-fill-matplotlib-bars-with-a-gradient) – wflynny

Antwort

1

Werfen Sie einen Blick auf die gradient_bar.py Beispiel aus der matplotlib Dokumentation.

Die Grundidee ist, dass Sie von pyplot verwenden, um die hist() Methode nicht, sondern bauen die selbst BarChart von imshow() stattdessen verwenden. Das erste Argument zu imshow() enthält die Farbkarte, die in dem Feld angezeigt wird, das durch den extent argmument angegeben wird.

Hier ist eine vereinfachte Version des oben genannten Beispiels, die Sie auf die Spur bringen soll. Es verwendet die Werte aus Ihrem Excel-Beispiel und eine Farbkarte, die CSS colors 'dodgerblue' und 'royalblau' für einen linearen Farbverlauf verwendet.

from matplotlib import pyplot as plt 
from matplotlib import colors as mcolors 

values = [22, 15, 14, 10, 7, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1, 7] 

# set up xlim and ylim for the plot axes: 
ax = plt.gca() 
ax.set_xlim(0, len(values)) 
ax.set_ylim(0, max(values)) 

# Define start and end color as RGB values. The names are standard CSS color 
# codes. 
start_color = mcolors.hex2color(mcolors.cnames["dodgerblue"]) 
end_color = mcolors.hex2color(mcolors.cnames["royalblue"]) 

# color map: 
img = [[start_color], [end_color]] 

for x, y in enumerate(values): 
    # draw an 'image' using the color map at the 
    # given coordinates 
    ax.imshow(img, extent=(x, x + 1, 0, y)) 

plt.show()