2013-02-14 10 views
5

मैं अजगर में matplotlib के साथ एक बार साजिश बना रहा हूं, और मैं अतिव्यापी सलाखों के साथ एक समस्या का एक सा हो रही है ओवरलैपिंग:दो matplotlib में बार चार्ट गलत तरीके से

import numpy as np 
import matplotlib.pyplot as plt 

a = range(1,10) 
b = range(4,13) 
ind = np.arange(len(a)) 
width = 0.65 

fig = plt.figure() 
ax = fig.add_subplot(111) 

ax.bar(ind+width, a, width, color='#b0c4de') 

ax2 = ax.twinx() 
ax2.bar(ind+width+0.35, b, 0.45, color='#deb0b0') 

ax.set_xticks(ind+width+(width/2)) 
ax.set_xticklabels(a) 

plt.tight_layout() 

Barplot

मैं नीले रंग के सलाखों को सामने रखना चाहता हूं, लाल वालों को नहीं। एकमात्र तरीका मैंने अब तक ऐसा करने में कामयाब रहा है कुल्हाड़ी और ax2 को स्विच करना था, लेकिन फिर ylabels को उलट दिया जा रहा है, जो मैं नहीं चाहता। कुल्हाड़ी से पहले अक्ष 2 प्रस्तुत करने के लिए matplotlib को बताने का कोई आसान तरीका नहीं है?

इसके अतिरिक्त, दाईं ओर वाले ylabels plt.tight_layout() द्वारा काटा जा रहा है। क्या अभी भी tight_layout का उपयोग करते हुए इससे बचने का कोई तरीका है?

उत्तर

6

शायद एक बेहतर तरीका है जिसे मैं नहीं जानता; हालांकि, आप स्वैप ax और ax2 और भी इसी y -ticks के स्थान

ax.yaxis.set_ticks_position("right") 
ax2.yaxis.set_ticks_position("left") 

import numpy as np 
import matplotlib.pyplot as plt 

a = range(1,10) 
b = range(4,13) 
ind = np.arange(len(a)) 
width = 0.65 

fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.bar(ind+width+0.35, b, 0.45, color='#deb0b0') 

ax2 = ax.twinx() 
ax2.bar(ind+width, a, width, color='#b0c4de') 

ax.set_xticks(ind+width+(width/2)) 
ax.set_xticklabels(a) 

ax.yaxis.set_ticks_position("right") 
ax2.yaxis.set_ticks_position("left") 

plt.tight_layout() 
plt.show() 

enter image description here


साथ स्वैप कर सकते हैं वैसे, बजाय कर रही है गणित स्वयं, आप align='center' पैरामीट का उपयोग कर सलाखों को केंद्रित कर सकते हैं एर:

import numpy as np 
import matplotlib.pyplot as plt 

a = range(1,10) 
b = range(4,13) 
ind = np.arange(len(a)) 

fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.bar(ind+0.25, b, 0.45, color='#deb0b0', align='center') 

ax2 = ax.twinx() 
ax2.bar(ind, a, 0.65, color='#b0c4de', align='center') 

plt.xticks(ind, a) 
ax.yaxis.set_ticks_position("right") 
ax2.yaxis.set_ticks_position("left") 

plt.tight_layout() 
plt.show() 

(परिणाम अनिवार्य रूप से ऊपर के समान है।)

+0

धन्यवाद! वह चाल है। और टिप के लिए भी धन्यवाद! मैंने हमेशा सोचा कि बस इसे करने का एक आसान तरीका होना चाहिए .. – Conti

संबंधित मुद्दे