Home > Software engineering >  Adding elements to a chart with Matplot
Adding elements to a chart with Matplot

Time:07-22

ax = fig.gca()

pplt.grid(True)

pplt.plot(df['Date'], pivot, label="Pivot")

plt.show()

I'm drawing a graph with their code. df['Date'] returns 160 rows of data. the number from the pivot is still equal to

I want to add one more data to this.

plt.plot(df['Date'], ema, label="EMA", linestyle='dashed')

but the problem is that 160 rows are coming from df['Date'] but 100 rows of data is coming from ema and naturally it gives an error and does not generate the graph. The first 60 lines of ema are nan . what I want to do is pass the first 60 (or how many are empty) blanks and add them to the chart.

How can I do that?

Thanks

CodePudding user response:

If I understand your question correctly I would create an array with the correct dimension and fill it with the right values. Soimething like

ema_arr = np.zeros_like(df['Data'])
ema_arr.fill(np.nan)
ema_arr[-ema.size:] = ema
plt.plot(df['Date'], ema_arr, label="EMA", linestyle='dashed')

The first line creates an array the same length of df['Data'] and fills it with 0s The second line sets the last values of said array to the values of ema. Finally the third line plots it.

CodePudding user response:

I would add nan values to the front of your ema list based on the difference in length of the ema list and the dataframe df. Then you can just plot both the pivot and the ema plots on the same graph:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

### Create mock data
df = pd.DataFrame({"Date":np.arange(0,16)})
ema = [10, 11, 12, 13, 14, 15]
pivot = np.arange(0, 16)[::-1]
##############

# fill the ema lsit with nan values based on the length of df
ema = [np.nan] * (len(df) - len(ema))   ema 

plt.plot(df["Date"], ema, label = "ema")
plt.plot(df["Date"], pivot, label = "pivot")
plt.legend()
plt.show()

Output:

both

If you just want the ema list plotted but want the range of x axis to be the same as the plot for the pivot table, then pass the xlim argument using the min value and max value of df["Date"]:

plt.plot(df["Date"], ema, label = "ema")
plt.xlim(df["Date"].min(), df["Date"].max())
plt.legend()
plt.show()

Output:

single

  • Related