Search code examples
pythonpandasmatplotlibplotlabel

Twinx makes labels disappear


I have an issue with setting the x labels while using twinx function. My original data is a pandas dataframe, namely, df, which has 3 attributes, "name"=product name, "sold"=number of items sold, and "revenue". the name is a pandas series (like "2 shampoo"), but I can't set it to be x tick label (see pic below). How could I set the x labels to display the product's names?

fig = plt.figure()  # Create matplotlib figure

    ax = fig.add_subplot(111)  # Create matplotlib axes
    ax2 = ax.twinx()  # Create another axes that shares the same x-axis as ax.

    width = 0.4

    df.sold.plot(kind='bar', color='red', ax=ax, width=width, position=1, rot=90)
    df.revenue.plot(kind='bar', color='blue', ax=ax2, width=width, position=0, rot=90)

    # print(type(df['name']), "\n", df['name'])

    ax.set_ylabel('Sold')
    ax2.set_ylabel('Revenue')
    ax.legend(['Sold'], loc='upper left')
    ax2.legend(['Revenue'], loc='upper right')
    plt.show()

enter image description here


Solution

  • You will need to set the labels for X-axis using the set_xticklabels() to show the fields. Add this line after plotting the graph.

    ax.set_xticklabels(df.Name)
    

    and you will get the below plot.

    enter image description here