2017-03-18 11 views
1

Ich versuche, ein vertikales Balkendiagramm von% Sprecher von 5 gesprochenen Sprachen in der Welt zu erstellen, mit Matplotlib. Um die höchste gesprochene Sprache besser hervorzuheben, habe ich die Farbe der Leiste geändert. Ich möchte auch das entsprechende X-Achsen-Tick-Label zu einer dunkleren Farbe ändern. Alles funktioniert gut, außer dass ich die Farbe der X-Achsen-Tick-Label nicht ändern kann.

Meine Software:Matplotlib - Ändern der Farbe einer einzelnen X-Achse Tick-Label

Windows-
Anaconda 4.3.0 x64, mit:
- IPython 5.1.0
- Python 3.6.0
- matplotlib 2.0.0
- Spyder 3.1 .3


Was ich versucht habe/Fehlerbehebung:

Ich habe die Lösung unter Formatting only selected tick labels mit plt.gca().get_xticklabels().set_color() versucht, die aussieht, wie es genau das tut, was ich will ,. Leider ist dies nicht die Farbe des Etiketts x-Achse ticks ändern, auch wenn der Farbwert zu ändern scheint:

#Does not change label color, but does show red when called 
print("Color before change: " + plt.gca().get_xticklabels()[-3].get_color()) 
plt.gca().get_xticklabels()[-3].set_color('red') #Does not change the label 
print("Color after change: " + plt.gca().get_xticklabels()[-3].get_color()) #Does show the value as 'red' 

Da die Kommentare bestätigen, wird das x-Achse tick Etikett nicht rot, aber die. get_color() -Methode zurückgibt red:

Color before change: grey 
Color after change: red 

habe ich versucht, den Index der get_xticklabels()[index] variiert, aber alle von ihnen scheinen das gleiche zu tun wie aufgeführt.

Die Antwort über die Indizierung erwähnt, ist nicht immer geradlinig, also habe ich die Textwerte der x-Achse Strichbeschriftungen durch Ausdrucken eine Fehlersuche durch getan:

for item in plt.gca().get_xticklabels(): 
    print("Text: " + item.get_text()) 

Jedes Element kommt wieder leer:

In [9]: runfile('x') 
Text: 
Text: 
Text: 
Text: 
Text: 
Text: 
Text: 

Es scheint mir, die Etiketten woanders festgehalten werden, oder vielleicht noch nicht aufgefüllt werden. Ich habe versucht, mit und get_xminorticklabels() herumspielen mit ähnlichen Ergebnissen.

Ich habe auch versucht, eine Liste der Farben direkt auf den labelcolor Parameter übergeben:

label_col_vals = ['grey','grey','black','grey','grey'] 
plt.gca().tick_params(axis='x', labelcolor=label_col_vals) 

Aber das nur zurückgibt, was ich nehme an, die Speicherstelle der Figur sein:

<matplotlib.figure.Figure at 0x14e297d69b0> 

Diese

ValueError: could not convert string to float: 'grey' 
: wenn versucht, einzelne x-Achse tick Etikettenfarben mit der get_xticklabels().set_color() Methode auch verursacht einen Fehler zu ändern

einen einzelnen Farbwert Passing (siehe unten) funktioniert, aber dies setzt alle der x-Achse Strichbeschriftungen die gleiche Farbe sein:

plt.gca().tick_params(axis='x', labelcolor='grey') 


Frage:

Wie kann ich die Farbe eines einzelnen X-Achsen-Tick-Labels ändern? Eine Liste an labelcolor zu übergeben oder get_xticklabels().set_color() zu arbeiten wäre vorzuziehen, aber eine andere Methode wäre auch nett.


Code:

''' 
@brief autoprint height labels for each bar 
@detailed The function determines if labels need to be on the inside or outside 
of the bar. The label will always be centered with respect to he width of the 
bar 

@param bars the object holding the matplotlib.pyplot.bar objects 
''' 
def AutoLabelBarVals(bars): 
    import matplotlib.pyplot as plt 

    ax=plt.gca() 

    # Get y-axis height to calculate label position from. 
    (y_bottom, y_top) = ax.get_ylim() 
    y_height = y_top - y_bottom 

    # Add the text to each bar 
    for bar in bars: 
     height = bar.get_height() 
     label_position = height + (y_height * 0.01) 

     ax.text(bar.get_x() + bar.get_width()/2., label_position, 
       '%d' % int(height), 
       ha='center', va='bottom') 

import matplotlib.pyplot as plt 
import numpy as np 

plt.figure() 

''' 
@note data from https://www.ethnologue.com/statistics/size 
''' 
languages =['English','Hindi','Mandarin','Spanish','German'] 
pos = np.arange(len(languages)) 
percent_spoken = [372/6643, 260/6643, 898/6643, 437/6643, 76.8/6643] 
percent_spoken = [x*100 for x in percent_spoken] 

''' 
@brief change ba colors, accentuate Mandarin 
''' 
bar_colors = ['#BAD3C8']*(len(languages)-1) 
bar_colors.insert(2,'#0C82D3') 

bars = plt.bar(pos, percent_spoken, align='center', color=bar_colors) 

''' 
@brief Soften the other bars to highlight Mandarin 
''' 
plt.gca().yaxis.label.set_color('grey') 
label_colors = ['grey','grey','black','grey','grey'] 
#plt.gca().tick_params(axis='x', labelcolor=label_colors) #Does not work 
plt.gca().tick_params(axis='x', labelcolor='grey') #Works 


''' 
@brief Try to change colors as in https://stackoverflow.com/questions/41924963/formatting-only-selected-tick-labels 
''' 
# Try to output values of text to pinpoint which one needs changed 
for item in plt.gca().get_xticklabels(): 
    print("Text: " + item.get_text()) 

print(plt.gca().get_xticklabels()[0].get_text()) 

''' 
@warning If trying to set the x-axis tick labels via list, this code block will fail 
''' 
print("Color before change: " + plt.gca().get_xticklabels()[1].get_color()) 
plt.gca().get_xticklabels()[1].set_color('red') #Does not change the label 
print("Color after change: " + plt.gca().get_xticklabels()[1].get_color()) #Does show the value as 'red' 
''' 
@warning If trying to set the x-axis tick labels via list, this code block will fail 
''' 


plt.xticks(pos, languages) 
plt.title('Speakers of Select Languages as % of World Population') 

# remove all the ticks (both axes), and tick labels on the Y axis 
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on', color='grey') 

''' 
@brief remove the frame of the chart 
''' 
for spine in plt.gca().spines.values(): 
    spine.set_visible(False) 

# Show % values on bars 
AutoLabelBarVals(bars) 

plt.show() 

Antwort

2

Die Ticklabels können sich im Laufe des Skripts ändern. Es empfiehlt sich daher, die Farbe am Ende des Skripts festzulegen, wenn keine Änderungen mehr vorgenommen werden.

from __future__ import division 
import matplotlib.pyplot as plt 
import numpy as np 

def AutoLabelBarVals(bars): 
    ax=plt.gca() 
    (y_bottom, y_top) = ax.get_ylim() 
    y_height = y_top - y_bottom 
    for bar in bars: 
     height = bar.get_height() 
     label_position = height + (y_height * 0.01) 
     ax.text(bar.get_x() + bar.get_width()/2., label_position, 
       '%d' % int(height), 
       ha='center', va='bottom') 
plt.figure() 
languages =['English','Hindi','Mandarin','Spanish','German'] 
pos = np.arange(len(languages)) 
percent_spoken = [372/6643, 260/6643, 898/6643, 437/6643, 76.8/6643] 
percent_spoken = [x*100 for x in percent_spoken] 
bar_colors = ['#BAD3C8']*(len(languages)-1) 
bar_colors.insert(2,'#0C82D3') 
bars = plt.bar(pos, percent_spoken, align='center', color=bar_colors) 
plt.gca().yaxis.label.set_color('grey') 
plt.gca().tick_params(axis='x', labelcolor='grey') #Works 
plt.xticks(pos, languages) 
plt.title('Speakers of Select Languages as % of World Population') 
plt.tick_params(top='off', bottom='off', left='off', right='off', 
       labelleft='off', labelbottom='on', color='grey') 
for spine in plt.gca().spines.values(): 
    spine.set_visible(False) 
AutoLabelBarVals(bars) 

plt.gca().get_xticklabels()[1].set_color('red') 

plt.show()
1

Der Aufruf von plt.tick_params mit color='grey' die Farbeinstellung wird überschrieben wird.

Ihre Druckanweisungen funktionieren nicht, da sie auftreten, bevor Sie die X-Tick-Etiketten mit plt.xticks() festlegen. Verschieben Sie diese beiden Zeilen direkt nach dem Anruf an plt.bars und Ihr Code sollte funktionieren.

bars = plt.bar(pos, percent_spoken, align='center', color=bar_colors) 

plt.xticks(pos, languages) 
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on', color='grey') 
+0

Leider hat dies in meiner Situation nicht funktioniert. Ich habe versucht, die Indizes zu variieren, um zu sehen, ob ich das falsche Element anrufe, aber immer noch kein Glück. Danke für den Vorschlag, aber es kann in zukünftigen Ausgaben nützlich sein. –

+0

Sorry das war nicht richtig. Ich mache mehr graben. – Craig

+0

Danke fürs schauen. Wenn es hilft, konnte ich Ihr Code-Snippet mit den gewünschten Ergebnissen reproduzieren. Ich nehme an, dies bedeutet, dass es nicht meine Einstellung ist, die das Problem verursacht. –

Verwandte Themen