How to separate points in the x axis graphic with matplotlib?

I'm learning to use Python, and as homework we're supposed to read a CSV file related to Covid-19 data.

import pandas as pd
import matplotlib.pyplot as plt

def graficarUnPais (data, pais):
    x1 = []
    y1 = []
    x2 = []
    y2 = []

    for record in data:
        if (record['location'] == pais):
            if ((not (mt.isnan(record['total_cases'])))):
                x1.append(record['date'])
                y1.append(record['total_cases'])
            if ((not (mt.isnan(record['total_deaths'])))):
                x2.append(record['date'])
                y2.append(record['total_deaths'])

    plt.title("Casos y Muertes Totales")
    plt.xlabel('Día')
    plt.ylabel('Casos')
    plt.plot(x1, y1, label='Casos Totales')
    plt.plot(x2, y2, label='Muertes Totales')
    plt.xticks(rotation=90)
    plt.legend()
    plt.show()

archivo = pd.read_csv('full_data.csv')
data_list = archivo.to_dict("list")
data_records = archivo.to_dict("records")

paises = 'Argentina'
graficarUnPais(data_records, pais)

So the graphic is correct but, I don't like the format, the dates are all smashed up. I wonder if there is a way to separate all the x axis points a little more. I'm using PyCharm by the way.

I don't know if there is a way to put like a horizontal scrollbar or something like that

Here is a picture of the graphic:

Graphic

Upvotes: 0

Views: 752

Answers (1)

Ed Smith
Ed Smith

Reputation: 13216

There are lots of options, including setting the values you want to show as an xtick array (see e.g. Changing the "tick frequency" on x or y axis in matplotlib?). In your case you could simple use,

skip = 5
plt.xticks(x1[::skip]))

Note I assume x1=x2. However, the right way to do this may be to use the concise data formatter function,

https://matplotlib.org/3.1.0/gallery/ticks_and_spines/date_concise_formatter.html

EDIT: If you really want a slider to focus on a bit of the whole, you could do the following,

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import matplotlib.dates as mdates
import datetime as dt


window = 20

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.25)

#Generating dates using https://stackoverflow.com/questions/9627686/plotting-dates-on-the-x-axis-with-pythons-matplotlib
N = 100
y = np.random.rand(N)
now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=5))
ax.plot(days, y)


axshow = plt.axes([0.25, 0.1, 0.65, 0.03])
s = Slider(axshow, 'Range', 0, N, valinit=0, valstep=1)


def update(val):
    ax.set_xlim(days[int(val)],days[int(val)+window])

s.on_changed(update)
fig.show()

Which lets you choose with a slider,

enter image description here

Upvotes: 1

Related Questions