While working with seaborn, I tried to set x-ticks to be different from my data unsuccessfully. I'll give concrete example in a moment, but I also generalized my question. If there is a canonical answer to the general question that will be great.
Is it possible to set x-ticks to be a function of the data what I used for plotting? When I can't plot function of data directly.
- Assume I've a method which receive
x
and returnsf(x)
. Is it possible to plot data byx
, but showingf(x)
in x axis? Like returning a string for each number, and I want to show the string. - If I have a dataframe which I plot as x-axis his column name "col_x", and I want instead of that x-ticks to show data of "col_f_x". Can I make somehow a "match" between two columns?
Questions are similar of course, while the first assumes I have a function, the second asks directly about two columns in dataframe.
Now for concrete example. My initial goal was to use seaborn.displot
on dates. Unfortunately, it seems it does not support working with dates. I decided to do some bypass and plot data by days difference. I explained what I did here: How to plot Pandas datetime series in Seaborn distplot?
, that is the origin of my question.
Let's use this simple example:
import pandas as pd
import datetime as dt
original_dates = ["2016-03-05", "2017-03-05", "2016-02-05", "2016-02-05", "2016-02-05", "2015-03-05"]
dates_list = [dt.datetime.strptime(date, '%Y-%m-%d').date() for date in original_dates]
df = pd.DataFrame({"Date":dates_list})
df["NewDate"] = df["Date"] - dt.date(2015,3,5)
df["NewDate"] = df["NewDate"].apply(lambda x: x.days)
import seaborn as sns
sns.set()
ax = sns.distplot(df['NewDate'])
Output:
I used numerical different of days instead of plotting Date column directly. But I want my xticks to be dates, not numerical difference. How can I do this?
I hope my two general questions are now more clearer: I can supply to the plot a function (date - starting_date) or different column (Date), by I'm still not sure how to set x-ticks accordingly.
During my small research on that I tackled across matplotlib's major_locator
and major_formatter
. I guess I suppose to use them, but couldn't figure out how to do it on my own. Some of related posts in stack overflow I found during my search:
Manipulating Dates in x-axis Pandas Matplotlib
matplotlib set xticks to column, labels to corresponding index