2016-10-21 4 views
1

Mein Problem:Wie zentriert Liniendiagramm mit Balkendiagramm in MatPlotLib?

Ich havinging difficutly versucht, meine Liniendiagramm mit der y Zecken zentriert zu bekommen. Zur Zeit scheint es einen Versatz nach links zu geben, wenn ich meine Graphen zeichne. Außerdem habe ich Schwierigkeiten damit, beide Labels in der gleichen Legende erscheinen zu lassen.

Mein Code:

f, ax1 = plt.subplots(1, figsize=(10, 5)) 

# Set the bar width 
bar_width_tram = 1 
bar_width_brake_percentage = 1 

# Positions of the left bar-boundaries 
bar_l = [i + 1 for i in range(len(data_frame['Tram Hrs']))] 

# Positions of the x-axis ticks (center of the bars as bar labels) 
tick_pos = [i + (bar_width_tram/2) for i in bar_l] 

# Define the colours for the corresponding 
# bars in the graph 
tram_data_hrs_colour = '#00AC00' # Green 
bd_per_colour = '#DA0505' # Red 

# Create a bar plot, in position bar_1 
ax1.bar(bar_l, 
     # using the pre_score data 
     data_frame['Tram Hrs'], 
     # get rid of border lines 
     edgecolor="none", 
     # set the width 
     width=bar_width_tram, 
     # with the label pre score 
     label='Tramming Hours', 
     # with alpha 0.5 
     alpha=0.05, 
     # with color 
     color=tram_data_hrs_colour) 


    # Set the X-ticks with dates 
    plt.xticks(tick_pos, data_frame['Date']) 

    plt.yticks(np.arange(0, 15, 3)) 

    # Set the labels and legend 
    ax1.set_ylabel("Tramming Time (Hours)") 
    ax1.set_xlabel("Previous Week") 

    # Second axis 
    ax2 = ax1.twinx() 
    ax2.set_ylabel("Braking to Tramming (%)") 

    plt.plot(bar_l,data_frame['Brake%'], '-', label='Relative Braking Percentage') 

    plt.yticks(np.arange(0, 250, 50)) 

    # Set the title of the chart 
    plt.legend(loc='upper left') 

Above-Code Ausgänge: enter image description here

Meine Fragen:

Q1. Wie kann ich erreichen, dass das Liniendiagramm mit den X-Tics in den Balkendiagrammen entlang der X-Achse zentriert/ausgerichtet ist (d. H. Aktuell sind sie links vorgespannt)?

Q2. Wie kann ich beide Beschriftungen in der Legende anzeigen lassen?

Mein Ideal Ausgang: enter image description here

Daten:

Date Brake Hrs Tram Hrs Brake% Tram% Br/Tr% 
0 Mon  0.87  4.26 16.90 83.10 20.33 
1 Tue  1.00  3.05 24.66 75.34 32.73 
2 Wed  1.77  3.87 31.44 68.56 45.85 
3 Thu  1.86  5.16 26.44 73.56 35.94 
4 Fri  1.41  2.01 41.15 58.85 69.93 
5 Sat  0.01  5.03 0.14 99.86 0.14 
6 Sun  0.40  1.16 25.82 74.18 34.82 

Mit Spalten Date für x-Achse und Tram Hrs Achse 1, Br/Tr% für Achse 2

+0

Könnten Sie mir einen vollständigen Code geben – SSN

+0

@SatheeshSivaNallathambi Die Daten werden aus der Datenbank extrahiert - ich kann den Datensatz mit Ihnen teilen, wenn Sie möchten? – 3kstc

Antwort

2

Q1 betrifft, Was Sie tun müssen, ist, die Balkenausrichtung einzustellen und hinzuzufügen align = 'center' zum Aufruf von ax.bar (http://matthiaseisen.com/pp/patterns/p0177/)

Für Q2 können Sie dieser SO-Antwort folgen: Single legend for multiple axes.

Schließlich habe ich unten einen Aufruf von plt.xlim hinzugefügt, um Leerraum auf beiden Seiten des Diagramms zu lassen.

Anbei finden Sie unten vorgeschlagene Lösung und Ausgang erhalten:

import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 

cols = ['Date', 'Brake Hrs', 'Tram Hrs', 'Brake%', 'Tram%', 'Br/Tr%'] 
data_frame = pd.DataFrame([['Mon',  0.87,  4.26, 16.90, 83.10, 20.33], 
          ['Tue',  1.00,  3.05, 24.66, 75.34, 32.73], 
          ['Wed',  1.77,  3.87, 31.44, 68.56, 45.85], 
          ['Thu',  1.86,  5.16, 26.44, 73.56, 35.94], 
          ['Fri',  1.41,  2.01, 41.15, 58.85, 69.93], 
          ['Sat',  0.01,  5.03, 0.14, 99.86, 0.14], 
          ['Sun',  0.40,  1.16, 25.82, 74.18, 34.82]], 
         columns = cols) 



f, ax1 = plt.subplots(1, figsize=(10, 5)) 

# Set the bar width 
bar_width_tram = 1 
bar_width_brake_percentage = 1 

# Positions of the left bar-boundaries 
bar_l = [i + 1 for i in range(len(data_frame['Tram Hrs']))] 

# Positions of the x-axis ticks (center of the bars as bar labels) 
tick_pos = [i + (bar_width_tram/2) for i in bar_l] 

# Define the colours for the corresponding 
# bars in the graph 
tram_data_hrs_colour = '#00AC00' # Green 
bd_per_colour = '#DA0505' # Red 

# Create a bar plot, in position bar_1 
ax1.bar(bar_l, 
     # using the pre_score data 
     data_frame['Tram Hrs'], 
     # get rid of border lines 
     edgecolor="none", 
     # set the width 
     width=bar_width_tram, 
     # with the label pre score 
     label='Tramming Hours', 
     # with alpha 0.5 
     alpha=0.05, 
     # with color 
     color=tram_data_hrs_colour, 
     align = 'center') 


# Set the X-ticks with dates 
plt.xticks(tick_pos, data_frame['Date']) 

plt.yticks(np.arange(0, 15, 3)) 

# Set the labels and legend 
ax1.set_ylabel("Tramming Time (Hours)") 
ax1.set_xlabel("Previous Week") 

# Second axis 
ax2 = ax1.twinx() 
ax2.set_ylabel("Braking to Tramming (%)") 

plt.plot(bar_l,data_frame['Brake%'], '-', label='Relative Braking Percentage') 

plt.yticks(np.arange(0, 250, 50)) 

# Set the title of the chart 
h1, l1 = ax1.get_legend_handles_labels() 
h2, l2 = ax2.get_legend_handles_labels() 
ax1.legend(h1+h2, l1+l2, loc=2) 

plt.xlim(0, len(tick_pos) + 1) 

enter image description here

Dies steht in Einklang mit der gewünschten Ausgabe sieht. Ich benutze Matplotlib 1.5.1 und Pandas 0.18.1

+0

Die Legende funktionierte, aber die Liniendiagramme sind immer noch nach links versetzt. Ich habe 'align =' center' 'mit 'plt.plot (bar_l, data_frame [' Brake% '],' - ', label =' Relative Braking Percentage ') versucht, aber es hat nicht funktioniert ... Irgendwelche Empfehlungen ? – 3kstc

+0

Ich habe mein vollständiges Skript gepostet, also könnte es einfacher für Sie sein, es zu testen. Ich musste nur "align = 'center'" im ersten Aufruf von ax1.bar hinzufügen und das Liniendiagramm automatisch anpassen – FLab

+0

danke, aber mit mir habe ich einige Abstände an beiden Enden der [Graphen] (https: // s17 .postimg.org/oc5ev21y7/grafhabcdef.png). Wie kann ich dieses speacing in beide Enden in deinen Code integrieren?Ich bin sehr neu zu Matplotlib, – 3kstc

Verwandte Themen