Home > Backend Development > Python Tutorial > How Can I Prevent Overlapping Time Stamp Labels on Matplotlib X-Axis?

How Can I Prevent Overlapping Time Stamp Labels on Matplotlib X-Axis?

Susan Sarandon
Release: 2024-12-26 04:09:10
Original
351 people have browsed it

How Can I Prevent Overlapping Time Stamp Labels on Matplotlib X-Axis?

Rotating Axis Tick Labels for Non-Overlapping Time Stamps

When dealing with time-stamped data, the increasing number of samples often leads to cluttered and overlapping tick labels on the X axis. To prevent this and improve readability, rotating these labels can be beneficial.

Solution:

To rotate the X axis tick labels, you can simply append plt.xticks(rotation=90) to your existing code. This will rotate the labels by 90 degrees, making them vertical and less likely to overlap.

Code Snippet:

Below is your code with the addition of the plt.xticks(rotation=90) line to rotate the X axis tick labels:

import sys

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import datetime

font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 8}

matplotlib.rc('font', **font)

values = open('stats.csv', 'r').readlines()

time = [datetime.datetime.fromtimestamp(float(i.split(',')[0].strip())) for i in values[1:]]
delay = [float(i.split(',')[1].strip()) for i in values[1:]]

plt.plot(time, delay)
plt.grid(b='on')
plt.xticks(rotation=90)  # Rotate the X axis tick labels by 90 degrees

plt.savefig('test.png')
Copy after login

By incorporating this line into your code, the X axis tick labels will be displayed vertically and more legible, even as the time stamps become more frequent and closer together.

The above is the detailed content of How Can I Prevent Overlapping Time Stamp Labels on Matplotlib X-Axis?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template