0
votes

I'm plotting a dataframe in seaborn with 2 (datetime) points separated by a week. What I want is 2 points on the x axis but seaborn is giving 7 which is messy and confusing.

    import matplotlib.pyplot as plt
    import seaborn as sns
    import datetime
    import pandas as pd

    df = pd.DataFrame.from_dict({'Branch': {0: 'Branch 1', 1: 'Branch 1'}, 'Value £': {0: 24.0, 1: 7.5},
 'W/c': {0: datetime.date(2019, 5, 27), 1: datetime.date(2019, 6, 3)}})

    df
   Branch         W/c  Value £
0  Branch 1  2019-05-27     24.0
1  Branch 1  2019-06-03      7.5



    sns.set()
    fig, ax = plt.subplots()
    pd.plotting.register_matplotlib_converters(explicit=True)
    ax = sns.lineplot(data = df,  x='W/c', y='Value £', hue='Branch')
    fig.savefig('plot.png', bbox_inches='tight')

Expected result: 2 points on the x axis

Actual result: 7 points on x axis (each day between and including the dates in the df).

How do I get just 2 values on the x axis?

Thanks

1
Are you maybe looking for a pointplot instead?ImportanceOfBeingErnest
Point plot does the trick - many thanks.user2839288

1 Answers

0
votes

You can hide all but the first and the last tick labels using the following. Here range(1, len(xtcks)-1) will loop from 2nd tick up to the second last tick and make their labels hide



Complete answer

import matplotlib.pyplot as plt
import seaborn as sns
import datetime
import pandas as pd

df = pd.DataFrame.from_dict({'Branch': {0: 'Branch 1', 1: 'Branch 1'}, 'Value £': {0: 24.0, 1: 7.5},
                             'W/c': {0: datetime.date(2019, 5, 27), 1: datetime.date(2019, 6, 3)}})


sns.set()
fig, ax = plt.subplots()
pd.plotting.register_matplotlib_converters(explicit=True)
ax = sns.lineplot(data = df,  x='W/c', y='Value £', hue='Branch')
fig.canvas.draw()

xticks = ax.xaxis.get_major_ticks()
for i in range(1, len(xticks)-1):
    xticks[i].label1.set_visible(False)

fig.savefig('plot.png', bbox_inches='tight')

enter image description here