Python Forum

Full Version: Having trouble setting the X-Ticks for a data set I am working with.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am using a large data set that, it contains homelessness numbers in NYC from 08/21/2013 to 01/16/2024 and when I graph it normally it gives a unreadable mess due to the amount of dates. I tried using various things to remove most of the dates such as "set_xticks" and others but I keep getting this error message:
"'DataFrame' object has no attribute 'set_xticks'"

my code is the following:
"plt.figure(figsize=(10,10))
sns.lineplot(data=homelessness_data, x='Date of Census', y='Total Individuals in Shelter')
homelessness_data.set_xticks(['01/01/2013', '01/01/2014', '01/01/2015', '01/01/2016', '01/01/2017', '01/01/2018','01/01/2019', '01/01/2020', '01/01/2021','01/01/2022', '01/01/2023' ])" I have read through multiple stack overflow stuff but it still isnt working.
can anyone help?
I attached the CSV im using in case that helps. I can also answer any following questions one may have.
My guess is that Date of Census in your homelessness_data is not a datetime or date object. I read your data like this:
import pandas as pd

data = pd.read_csv("census.csv")
print(data.dtypes)
Output:
Date of Census object Total Individuals in Shelter int64 Total Single Adults in Shelter int64 Families with Children in Shelter int64 Adult Families in Shelter int64 dtype: object
Notice that Date of Census is an "object", which is a string. You need Date of Census to be a date, then seaborn/matplotlib can create ticks that are reasonable in count and distribution because it will know what the tics mean.

Compare the plot produced by this code:
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("census.csv")
data.plot(x="Date of Census", y="Total Individuals in Shelter")
plt.show()
With the plot produced by this code.
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("census.csv", parse_dates=["Date of Census"])
data.plot(x="Date of Census", y="Total Individuals in Shelter")
plt.show()
Matplotlib usually does a good job making tic marks and labels. When something goes wrong it is usually because you are not providing enough information for matplotlib to make good decisions.

I think this will fix your problem, but if you do want to set labels and the like (which is almost always a bad idea), you do this using the Axis object returned by sns.lineplot()