Home > Blockchain >  Python plot y axis avreage label won't show and the Dates ar all crowdet
Python plot y axis avreage label won't show and the Dates ar all crowdet

Time:09-23

I want to have a Label for the red y axis avreage line but it wont show up as a label. Also all the Dates from the dataset are all crowdet

This is my Code:

def plot_data(measurement):


    df = pd.read_csv("out.csv")
    date = df["date"]
    value = df[measurement]

    plt.plot(date, value, label=host[0:7]   ", "   measurement   ", "   date_til[0:10]   " "    date_from[11:19]   "-"   date_til[11:19])
    plt.title(measurement)
    plt.xlabel("date")
    plt.ylabel(measurement)
    plt.legend()
    plt.xticks(rotation=45)

    average = df[measurement].mean()

    plt.axhline(y=average, color='r', linestyle='-', label="average Ø ≈ "   str(average))

    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5, forward=True)

    #today = date.today()
    #print(today)
    filename = "plots/plot_"   date_from[0:10]   ".png"

    fig.savefig(filename, dpi=100)

    print("\rPlot: Done ✔️")

This is the resullt of the plot: broken_plot

CodePudding user response:

In order to show average Ø ≈ ... label in legend you need to call plt.legend after ax.axhline:

...

average = df[measurement].mean()

plt.axhline(y=average, color='r', linestyle='-', label="average Ø ≈ "   str(average))

plt.legend()

...

x axis label crowding happens when you are plotting x axis as str in place of datetime, so you need to do this conversion with enter image description here

df = pd.read_csv(r'data/data.csv')
df['date'] = pd.to_datetime(df['date'])

fig, ax = plt.subplots()

ax.plot(df['date'], df['value'])

plt.show()

enter image description here


You can further customize x axis ticks with:

import matplotlib.dates as md

# set spacing between ticks
ax.xaxis.set_major_locator(md.HourLocator(interval = 3))

# set tick label format
ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S'))

# set tick label rotation to 45°
plt.setp(ax.xaxis.get_majorticklabels(), rotation = 45)

enter image description here

  • Related