JocHwo
JocHwo

Reputation: 119

Plot with seaborn, not show all in x axis

I made a plot with seaborn, but I need the x-axis show the dates every 3 days (because my original df have more than 1000 registers), but only for estetical reasons, because it's important in the plot the line show all register (only modify the x-ticks).

This is a df

import matplotlib.pyplot as plt
data = {'Sales':  [10,30,20,55,78,90,22,42,53,14,11,31,32,21,20,42],
        'Date': ['2020-03-03', '2020-03-04','2020-03-05','2020-03-06','2020-03-07', '2020-03-08','2020-03-09','2020-03-10','2020-03-11', '2020-03-12','2020-03-13','2020-03-14','2020-03-15', '2020-03-16','2020-03-17','2020-03-18']}
df = pd.DataFrame (data, columns = ['Date','Sales'])
plt.figure(figsize=(16,10))

chart = sns.lineplot(data=df,x='Date',y='Sales',palette='Set1')

plt = plt.xticks(rotation=45,horizontalalignment='right',fontweight='light')

enter image description here

I need something like this:

Solution

Thanks a lot!!

Upvotes: 0

Views: 7579

Answers (2)

mullinscr
mullinscr

Reputation: 1738

You can use matplotlib's dates locator and formatter to do nearly every conceivable timeline styling/locating you want -- see the docs.

In your case we can use the day locator and set the interval to 3 days. You will have to import matplotlib.dates too.

import matplotlib.dates as mdates.

Now add this before plt.show():

locator = mdates.DayLocator(interval=3)
chart.xaxis.set_major_locator(locator)

So altogether it looks like this

import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as mdates

ata = {'Sales':  [10,30,20,55,78,90,22,42,53,14,11,31,32,21,20,42],
        'Date': ['2020-03-03', '2020-03-04','2020-03-05','2020-03-06','2020-03-07', '2020-03-08','2020-03-09','2020-03-10','2020-03-11', '2020-03-12','2020-03-13','2020-03-14','2020-03-15', '2020-03-16','2020-03-17','2020-03-18']}
df = pd.DataFrame (data, columns = ['Date','Sales'])
plt.figure(figsize=(16,10))

chart = sns.lineplot(data=df,x='Date',y='Sales',palette='Set1')

plt.xticks(rotation=45,horizontalalignment='right',fontweight='light')

locator = mdates.DayLocator(interval=3)
chart.xaxis.set_major_locator(locator)

plt.show()

Upvotes: 2

RobinFrcd
RobinFrcd

Reputation: 5396

You can take only even date rows, it should be enough:

import matplotlib.pyplot as plt
import seaborn as sns

data = {'Sales':  [10,30,20,55,78,90,22,42,53,14,11,31,32,21,20,42],
        'Date': ['2020-03-03', '2020-03-04','2020-03-05','2020-03-06','2020-03-07', '2020-03-08','2020-03-09','2020-03-10','2020-03-11', '2020-03-12','2020-03-13','2020-03-14','2020-03-15', '2020-03-16','2020-03-17','2020-03-18']}
df = pd.DataFrame (data, columns = ['Date','Sales'])
plt.figure(figsize=(16,10))

chart = sns.lineplot(data=df,x='Date',y='Sales',palette='Set1')

plt.xticks(
    df['Date'].iloc[::2], # Odd rows only
    rotation=45,
    horizontalalignment='right',
    fontweight='light'
)
plt.plot()

Upvotes: 1

Related Questions