python matplotlib.pyplot doesn't rendering timeseries plot - python

ax.plot() doesn't render the time series plot, while pandas.plot() and plt.scatter() works. But because I need to reform my axis, I need to use ax.plot().
My data:
When I try to plot it:
ax=df_cuba['ORD'].plot()
It works perfectly:
But when I try to use :
plt.plot(x=df_cuba.index,y=df_cuba['ORD'])
It shows nothing:
It also works for scatterplot.
I couldn't find any posts about this. I suspect the py.plot is trying a different way to plot time series data.

plot does not have named x and y arguments. So suppose you have xdata and ydata you want to plot, you cannot use plt.plot(x=xdata, y=ydata), but instead need
plt.plot(xdata, ydata)
For scatter this is different, here you can use both
plt.scatter(xdata, ydata)
plt.scatter(x=xdata, y=ydata)

I found out the real reason: plt.plot can only plot numerical data, so if we want to plot the time series data with np.datetime64 or pd.datetime format, we need to use the following command:
plt.plot_date(date, y)

Related

python matplotlib not plotting y axis in order

I am very new to Python - I have a time series that I want to model, but I get stuck early on with simply plotting the time series. The plot seems to be ordering the y-axis in order of the numbers appearing:
plt.plot(model_data2['month'], model_data2['opening_position'], color='blue', linewidth=2)
plt.ylabel('Opening Position ($)')
plt.show()
I would greatly appreciate advise on how to correct this.
You're passing strings here, so yes, it assumes you gave them in the order you wanted them. It doesn't know how to plot the value of a string. Convert these to floats, and you will get the results you expect.

No lines in plot using matplotlib Python

Here is my code:
import matplotlib.pyplot as plt
t = np.array([[0,1,2,3,4,5,6,7,8,9,10,11,12]])
g1 = np.array([[2,2.2,3,4,3.5,4.3,4.9,6,7.9,9.9,9.5,9.6,10]])
plt.figure(1)
plt.plot(t,g1)
Nothing happens. plt.show() does not help. I know it's because I use double brackets in t and g1 but I need that for my script. How do keep my double brackets, i.e. dimensions, AND being able to plot?
EDIT: OK, I had to transpose them in order to plot them - is there no way that Python automatically detects that?? (I am used to Matlab where the dimensions in this regard doesn't matter for plotting)
You can squeeze the dimensions of t and g1 when you plot them:
plt.plot(t.squeeze(), g1.squeeze())
Squeezing removes all singleton dimensions, thus the plot is with 1-dimensional arrays.
You noticed that if you transpose it, the plot works. That's because matplotlib plots columns when you feed it 2d data. Plot makes lines and there are no lines to make when all the columns only have one value. Another way to see this is to make a scatter plot.
plt.plot(t, g1, 'o')

python matplotlib - retrieve xaxis_major_locator as time value

I am plotting a timeserie with matplotlib (timeserie looks like the following):
Part of the code that i use sets major locator for each day at 0AM:
fig, ax = plt.subplots(figsize=(20, 3))
mpf.candlestick_ohlc(ax,quotes, width=0.01)
ax.xaxis_date()
ax.xaxis.set_major_locator(mpl.dates.DayLocator(interval=1) )
I would like to plot a darker background on the chart for each day between 16pm and 8am, and planning to use axvspan for that task. Considering that axvspan takes as argument axvspan(xmin, xmax) I was wondering if it would be possible to retrieve the xaxis_major_locator as a x value in order to pass it to axvspan as axvspan(xmin=major_locator-3600s, xmax=major_locator+3600s)
Edit: I found that function in the docs: http://matplotlib.org/2.0.0rc2/api/ticker_api.html#matplotlib.ticker.Locator
If anyone knows how to returns a list of ticker location from the Xaxis_major with it let me know. Thanks.
Edit2: if i use print(ax.xaxis.get_major_locator()) i receive as a return <matplotlib.dates.DayLocator object at 0x7f70f3b34090> How do i extarct a list of tick location from that?
ok found it...
majors=ax.xaxis.get_majorticklocs()

Python matplotlib. Trying to plot binary signal, getting interpolation

Hey probably a simple question, but cant find the answer to this. I am monitoring a series of bits with a timestamp. I can plot the state of them just fine, but in the plots there are a skewed line between 0->1 and 1->0, where there should just be a straight line at the time they switch. How to avoid this skewed line? It makes it look like i have values in between when i dont.
EDIT: As pointed out below, using step instead of plot solves the problem. Thanks:)
You can use the plt.step function instead of plot,
import numpy as np
import matplotlib.pyplot as plt
def heaviside(x):
return .5*(np.sign(x)+1.)
x = np.linspace(0,100,10)
y = heaviside(np.random.random(10)-.5)
plt.step(x,y)
plt.ylim(-1.5,1.5)
plt.show()
which gives,
You can use a stemplot:
plt.stem(x, y)
or a step plot
plt.step(x, y)

matplotlib histtype='step' looses data

I am plotting a histogram using matplotlib, my code is bellow. In the second plot if i set the histtype='step' I loose three bins of the data and cannot work out why. Has anyone had this problem before? If I change the histtype='bar' the plot looks fine.See image attached.
Code 1:
plt.hist(DelB[Sp],bins=20,histtype='step',normed=True,label='Sp')
dd=np.concatenate((DelB[S0],DelB[E]))
plt.hist(dd,bins=15,color='g',histtype='step',normed=True,label='E+S0')
plt.xlim(0.4,2.3)
ylabel('normalized fraction',size=15)
plt.legend()
Code2:
plt.hist(DelB[Sp],bins=20,alpha=0.5,facecolor='blue',normed=True,label='Sp')
dd=np.concatenate((DelB[S0],DelB[E]))
plt.hist(dd,bins=15,alpha=0.5,facecolor='green',normed=True,label='E+S0')
plt.xlim(0.4,2.3)
plt.legend()
ylabel('normalized fraction',size=15)
Your axis limits in the second plot are different. You can't see bars that are below the image boundary. Adding plt.ylim(0,2) will solve the issue

Categories