Home > Software design >  How to plot my pandas dataframe in matplotlib?
How to plot my pandas dataframe in matplotlib?

Time:11-08

I have the following code:

import matplotlib.pyplot as plt
import numpy as np

import pandas as pd

data = pd.read_csv("Ari_atlag.txt", sep = '\t', header = 0)


#Num_array = pd.DataFrame(data).to_numpy()

print(data.head())
data.plot()
#data.columns = ['Date', 'Number_of_test', 'Avarage_of_ARI']
#print(Num_array)
plt.show()

Output:

     Date    Number_of_test    Avarage_of_ARI 
0  2011-01                22          0.568734
1  2011-02                 5          0.662637
2  2011-03                 0          0.000000
3  2011-04                 3          0.307692
4  2011-05                 6          0.773611

Process finished with exit code 0

and the plot.

But with this code in the plot, the x axis is the index. But I want to get Date in x axis.

How to plot the Date with Number_of_test and Date with Avarage_of_ARI

I think, I somehow should change string(date) to dates, but don't know how to do that.

Best

CodePudding user response:

Use x='Date' as parameter of plot:

df.plot(x='Date')
plt.show()

enter image description here

CodePudding user response:

Try this :

#Excutable example
df = pd.DataFrame({"Date" : ["2011-01", "2011-02", "2011-03", "2011-04", "2011-05"],
                   "Number_of_test" : [22, 5, 0, 3, 6],
                   "Avarage_of_ARI" : [0.568734, 0.662637, 0.000000, 0.307692,
                                       0.773611]})
df.Date = pd.to_datetime(df.Date)
df = df.set_index("Date")

Plot

data_ax1 = df.Number_of_test
data_ax2 = df.Avarage_of_ARI
fig, ax1 = plt.subplots()
        
ax1.set_ylabel('Number_of_test', color = 'tab:red')
ax1.plot(data_ax1, color = 'tab:red', linewidth= 0.5)
ax1.tick_params(axis = 'y',
                labelcolor= 'tab:red',
                length = 6, 
                width = 1, 
                grid_alpha=0.5)
    
ax2 = ax1.twinx()
ax2.set_ylabel('Avarage_of_ARI', color = 'tab:blue')
ax2.plot(data_ax2, color = 'tab:blue', linewidth = 0.5)
ax2.tick_params(axis='y', labelcolor = 'tab:blue')
fig.tight_layout()
plt.xticks(rotation=45)
plt.title("PLOT", fontsize = 15)

Result enter image description here

CodePudding user response:

You can set the index to the date column if that works for your data.

cols = ['Number_of_test','Avarage_of_ARI']

data.set_index('Date', inplace = True)

for c in cols:
    data[c].plot()
  • Related