Изменение меток x в seaborn - PullRequest
1 голос
/ 19 июня 2020

Я пытаюсь изменить формат метки x-tick на формат даты (% m-% d).

Мои данные состоят из почасовых значений данных за определенный период дат. Я пытаюсь построить данные за 14 дней. Однако, когда я бегу, я получаю x меток полностью перемешанными.

введите описание изображения здесь

Есть ли способ показать только даты и пропустить почасовые значения на оси x. ? Есть ли способ изменить x тактов, когда я могу пропускать метки на несколько часов и показывать метки только для дат? Я использую seaborn.

После предложения из комментария я отредактировал свой код, чтобы построить график, как показано ниже:

fig, ax = plt.pyplot.subplots()
g = sns.barplot(data=data_n,x='datetime',y='hourly_return')
g.xaxis.set_major_formatter(plt.dates.DateFormatter("%d-%b"))

Но я получил следующую ошибку:

ValueError: DateFormatter found a value of x=0, which is an illegal 
date; this usually occurs because you have not informed the axis that 
it is plotting dates, e.g., with ax.xaxis_date()

После проверки столбца datetime я получаю следующий результат с типом данных столбца:

0     2020-01-01 00:00:00
1     2020-01-01 01:00:00
2     2020-01-01 02:00:00
3     2020-01-01 03:00:00
4     2020-01-01 04:00:00
          ...        
307   2020-01-13 19:00:00
308   2020-01-13 20:00:00
309   2020-01-13 21:00:00
310   2020-01-13 22:00:00
311   2020-01-13 23:00:00
Name: datetime, Length: 312, dtype: datetime64[ns]

Я подозревал, что тики x, поэтому, когда я запустил g.get_xticks() [который получает тики по оси x], Получил вывод в виде порядковых чисел. Кто-нибудь может сказать, почему это происходит?

1 Ответ

1 голос
/ 19 июня 2020

1. Подход к рисованию линейного графика с датой и временем по оси x

Можете ли вы попробовать изменить формат оси x, как показано ниже

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import dates

## create dummy dataframe
datelist = pd.date_range(start='2020-01-01 00:00:00', periods=312,freq='1H').tolist()
#create dummy dataframe
df = pd.DataFrame(datelist, columns=["datetime"])
df["val"] = [i for i in range(1,312+1)]
df.head()

Ниже приведена информация о фрейме данных

enter image description here

Draw plot

fig, ax = plt.subplots()
chart = sns.lineplot(data=df, ax=ax, x="datetime",y="val")
ax.xaxis.set_major_formatter(dates.DateFormatter("%d-%b"))

Output:

enter image description here

2. Approach for Drawing Bar plot using seaborn with x-axis datetime

There is a problem with the above approach if you draw for barplot. So, will use below code

fig, ax = plt.subplots()
## barplot
chart = sns.barplot(data=df, ax=ax,x="datetime",y="val")

## freq of showing dates, since frequency of datetime in our data is 1H. 
## so, will have every day 24data points
## Trying to calculate the frequency by each day 
## (assumed points are collected every hours in each day, 24)
## set the frequency for labelling the xaxis
freq = int(24)
# set the xlabels as the datetime data for the given labelling frequency,
# also use only the date for the label
ax.set_xticklabels(df.iloc[::freq]["datetime"].dt.strftime("%d-%b-%y"))
# set the xticks at the same frequency as the xlabels
xtix = ax.get_xticks()
ax.set_xticks(xtix[::freq])
# nicer label format for dates
fig.autofmt_xdate()

plt.show()

output:

введите описание изображения здесь

...