Nore Patel
Nore Patel

Reputation: 25

Flip x-axis of matplotlib graph

I am trying to flip the x-axis, it is listing dates and for some reason it has the most recent date close to the origin and earliest further to the right. I'm not sure why this happened. I tried including set(gca,'xdir','reverse','ydir','reverse') in the function below, but it didn't work, I got an error saying gca isn't found. Below is the code I have for the plot.

def plot_similarities(similarities_list, dates, title, labels):
    assert len(similarities_list) == len(labels)

    plt.figure(1, figsize=(10, 7))
    for similarities, label in zip(similarities_list, labels):
        plt.title(title)
        plt.plot(dates, similarities, label=label)
        plt.legend()
        plt.xticks(rotation=90)
    plt.show()

file_dates = {
    ticker: [ten_k['file_date'] for ten_k in ten_ks]
    for ticker, ten_ks in only_10ks_by_ticker.items()}  

plot_similarities(
    [cosine_similarities['AMD'][sentiment] for sentiment in sentiments],
    file_dates['AMD'][1:],
    'Cosine Similarities for {} Sentiment'.format('AMD'),
    sentiments)

What I would like is for the time values to be on the x-axis in ascending order, so earliest to the left and most recent to the right. Thanks!

Upvotes: 1

Views: 3839

Answers (1)

chris
chris

Reputation: 1322

You can grab the current axis and then invert:

ax=plt.gca()
ax.invert_xaxis()
ax.invert_yaxis()

Or you can store the axis object when plotting

ax=plt.plot(.....)
ax.invert_xaxis()
ax.invert_yaxis()

Upvotes: 4

Related Questions