Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

Xticks handling in python with seaborn and matplotlib.pyplot

I have a dataframe with a column "dates" which contains dates already converted into strings. In addition, every row of the dataframe has its own date (one per day basically, per 306 days), therefore when I plot with seaborn the x-axis' labels get dense and messy.

I was wondering if there was any way to only show fewer tickers, with just 5 dates (more or less) respecting the relationship between dates and data reported on the graph.

So far, I've tried this line of code to set the tickers:

plt.xticks(np.arange(12), cr.month_name[1:12], rotation=45)

however, the tickers and labels are plotted on the extreme left angle of the graph, as you can see in the following image:

enter image description here

What should I do to enhance the readability and clarity of my data with Seaborn?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One solution would be to use enumerate() to scan through the list of label positions and select the ones you want to display. Since I don't have access to your source code, here's an example of what I'm suggesting:

# Line plot, with a DataFrame indexed using strings containing dates in YYYY-MM-DD format.
plt_str = sns.lineplot(data=dataset_str)

curr_month = None
tickpos = []
ticklabel = []

for idx, label in enumerate(plt.get_xticklabels()):   
    # Parse datetime and reformat label as desired
    dateval = datetime.datetime.strptime(label.get_text(), '%Y-%m-%d')
    month = dateval.strftime('%b')
    
    # Clunky filter for identifying the first record for each month
    # Good enough for a proof-of-concept but consider revising.
    if month != curr_month:
        # We want this position, so stash its index and the month name
        tickpos.append(idx)
        ticklabel.append(month)

        curr_month = month

plt_str.set_xticks(tickpos)
plt_str.set_xticklabels(ticklabel, rotation=45)

Essentially, we just scan the list of labels and 'pick' the ones we want to keep by saving their index location and the label value we desire.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...