Search code examples
pythonmatplotlibaxis-labelsyaxis

Rotating & changing size of y-axis labels


I am trying to do a simple line of code just to rotate around the title label for readability.

Here is the block of code having imported the CSV file:

    ylabel_counter = 0
    ylabel_text = 'Sensor'
    ylabel_counter_str = ''

    df = pd.read_csv(root.filename)                      #Assume CSV file has bee selected and imported
    y = df['Total Force']
    x = df['Time Stamp']
    s_one = df['Sensor 1']
    s_two = df['Sensor 2']
    s_three = df['Sensor 3']
    s_four = df['Sensor 4']
    s_five = df['Sensor 5']
    s_six = df['Sensor 6']
    s_seven = df['Sensor 7']
    s_eight = df['Sensor 8']
    s_nine = df['Sensor 9']
    s_ten = df['Sensor 10']

    fig = plt.figure()
    gs = fig.add_gridspec(11, hspace=0.8, wspace=0)
    axs = gs.subplots(sharex=True, sharey=True)
    fig.suptitle('Forced Against Time')

    axs[0].plot(x, y)
    #axs[0].set_title('All Sensors', fontsize = 5)

    axs[1].plot(x, s_one)
    axs[2].plot(x, s_two)
    axs[3].plot(x, s_three)
    axs[4].plot(x, s_four)
    axs[5].plot(x, s_five)
    axs[6].plot(x, s_six)
    axs[7].plot(x, s_seven)
    axs[8].plot(x, s_eight)
    axs[9].plot(x, s_nine)
    axs[10].plot(x, s_ten)

    for ax in axs.flat:
        ylabel_number = ylabel_text + str(ylabel_counter)
        ax.set(xlabel='Time', ylabel=ylabel_number)                  #Area of interest, how to rotate set axes?
        ylabel_counter += 1
    
    for ax in axs:
        ax.label_outer()

    plt.show()

Here is the current plot of the graph, as seen in ylabel, the sensor labels are all overlapping so I am just trying to get them to rotate 90° to be just like the y-axis tick labels. Thanks in advance!

enter image description here


Solution

  • There is an option for labels rotation. Just set it equal to horizontal to get what you want. May have to break up your label command into two parts (x & y). Can't test because I can't run your example

    But something like

    ylabel_number = ylabel_text + str(ylabel_counter)
    ax.set_ylabel(ylabel_number, rotation='horizontal') 
    

    Additionally, to set the alignment, try set_label_coords like

    ax.yaxis.set_label_coords(-0.3, 0.5)  # where coord in axis coordinate frame
    

    see Matplotlib example https://matplotlib.org/stable/gallery/pyplots/align_ylabels.html