I have a dataframe as below:
frame_id time_stamp pixels step
0 50 06:34:10 0.000000 0
1 100 06:38:20 0.000000 0
2 150 06:42:30 3.770903 1
3 200 06:46:40 3.312285 1
4 250 06:50:50 3.077356 0
5 300 06:55:00 2.862603 0
I want to draw two y-axes in one plot. One is for pixels
. The other is for step
. x-axis is time_stamp. I want the plot for step
like the green line like this:
CodePudding user response:
Here's an example that could help. Change d1
and d2
as per your variables and the respective labels as well.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(seed=0)
d1 = rng.normal(loc=20, scale=5, size=200)
d2 = rng.normal(loc=30, scale=5, size=500)
fig, ax1 = plt.subplots(figsize=(9,5))
#create twin axes
ax2 = ax1.twinx()
ax1.hist([d1], bins=15, histtype='barstacked', linewidth=2,
alpha=0.7)
ax2.hist([d2], bins=15, histtype='step', linewidth=2,
alpha=0.7)
ax1.set_xlabel('Interval')
ax1.set_ylabel('d1 freq')
ax2.set_ylabel('d2 freq')
plt.show()
Getting the bar labels is not easy with the two types of histograms in the same plot using matplotlib.
CodePudding user response:
Instead of histograms you could use bar plots to get the desired output. I have also added in a function to help get the bar labels.
import matplotlib.pyplot as plt
import numpy as np
time = ['06:34:10','06:38:20','06:42:30','06:46:40','06:50:50','06:55:00']
step = [0,0,1,1,0,0]
pixl = [0.00,0.00,3.77,3.31,3.077,2.862]
#function to add labels
def addlabels(x,y):
for i in range(len(x)):
plt.text(i, y[i], y[i], ha = 'center')
fig, ax1 = plt.subplots(figsize=(9,5))
#generate twin axes
ax2 = ax1.twinx()
ax1.step(time,step, 'k',where="mid",linewidth=1)
ax2.bar(time,pixl,linewidth=1)
addlabels(time,step)
addlabels(time,pixl)
ax1.set_xlabel('Time')
ax1.set_ylabel('Step')
ax2.set_ylabel('Pixels')
plt.show()