Search code examples
pythonpandasdataframematplotlibfinance

How can I list sequentially the x and y axis on chart?


I have a dataframe and I want to show them on graph. When I start my code, the x and y axis are non-sequential. How can I solve it? Also I give a example graph on picture. First image is mine, the second one is what I want.

This is my code:


from datetime import timedelta, date
import datetime as dt #date analyse
import matplotlib.pyplot as plt
import pandas as pd #read file

def daterange(date1, date2):
    for n in range(int ((date2 - date1).days)+1):
        yield date1 + timedelta(n)
tarih="01-01-2021"
tarih2="20-06-2021"
start=dt.datetime.strptime(tarih, '%d-%m-%Y')
end=dt.datetime.strptime(tarih2, '%d-%m-%Y')
fg=pd.DataFrame()
liste=[]
tarih=[]
for dt in daterange(start, end):
    dates=dt.strftime("%d-%m-%Y")
    with open("fng_value.txt", "r") as filestream:
            for line in filestream:
                date = line.split(",")[0]
                if dates == date:
                    fng_value=line.split(",")[1]
                    liste.append(fng_value)
                    tarih.append(dates)
fg['date']=tarih
fg['fg_value']=liste
print(fg.head())
plt.subplots(figsize=(20, 10))
plt.plot(fg.date,fg.fg_value)
plt.title('Fear&Greed Index')
plt.ylabel('Fear&Greed Data')
plt.xlabel('Date')
plt.show()

This is my graph:

current graph

This is the graph that I want:

desired graph


Solution

  • Line plot with datetime x axis

    So it appears this code is opening a text file, adding values to either a list of dates or a list of values, and then making a pandas dataframe with those lists. Finally, it plots the date vs values with a line plot.

    A few changes should help your graph look a lot better. A lot of this is very basic, and I'd recommend reviewing some matplotlib tutorials. The Real Python tutorial is a good starting place in my opinion.

    Fix the y axis limit:

    plt.set_ylim(0, 100)
    

    Use a x axis locator from mdates to find better spaced x label locations, it depends on your time range, but I made some data and used day locator.

    import matplotlib.dates as mdates
    plt.xaxis.set_major_locator(mdates.DayLocator())
    

    Use a scatter plot to add data points as on the linked graph

    plt.scatter(x, y ... )
    

    Add a grid

    plt.grid(axis='both', color='gray', alpha=0.5)
    

    Rotate the x tick labels

    plt.tick_params(axis='x', rotation=45)
    

    I simulated some data and plotted it to look like the plot you linked, this may be helpful for you to work from.

    enter image description here

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    import matplotlib.dates as mdates
    
    fig, ax = plt.subplots(figsize=(15,5))
    
    x = pd.date_range(start='june 26th 2021', end='july 25th 2021')
    rng = np.random.default_rng()
    y = rng.integers(low=15, high=25, size=len(x))
    
    ax.plot(x, y, color='gray', linewidth=2)
    ax.scatter(x, y, color='gray')
    
    ax.set_ylim(0,100)
    ax.grid(axis='both', color='gray', alpha=0.5)
    ax.set_yticks(np.arange(0,101, 10))
    ax.xaxis.set_major_locator(mdates.DayLocator())
    ax.tick_params(axis='x', rotation=45)
    ax.set_xlim(min(x), max(x))