问题
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# create dataframes df0 and df1:
index0 = pd.date_range(start='2014-06-01 00:00:00', end='2014-06-01 00:15:00', freq='1S')
data0 = np.random.rand(len(index0))
df0 = pd.DataFrame(data=data0, index=index0, columns=['DF0'])
index1 = pd.date_range(start='2014-06-01 00:00:00', end='2014-06-01 00:15:00', freq='15S')
data1 = np.random.rand(len(index1))
df1 = pd.DataFrame(data=data1, index=index1, columns=['DF1'])
# plot df0 and df1:
fig,ax1 = plt.subplots(figsize=(40,10))
ax2 = ax1.twinx()
df0.plot.line( color="r", ax = ax1)
df1.plot.bar( color ='b', linewidth = 5, ax = ax2, alpha = 0.7)
plt.show()
I can overlay the dataframes as two line plots or as two barplots. But however hard I try, I can't manage to overlay a line plot with a bar plot or the other way round? With the code above I only get the barplot of df1 but don't see the lineplot of df0
. What do I have to do differently?
回答1:
bar
plot takes categorical (string) values only as the x values. hence simple hack can be converting the time stamps to strings.
when you feed the float values, it converts them into str thereby they are not matching with the index of line plot x-values.
df0.index = df0.index.map(str)
Secondary axis would also be not required for this.
Try this!
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# create dataframes df0 and df1:
index0 = pd.date_range(start='2014-06-01 00:00:00',
end='2014-06-01 00:15:00', freq='1S')
data0 = np.random.rand(len(index0))
df0 = pd.DataFrame(data=data0, index=index0, columns=['DF0'])
df0.index = df0.index.map(str)
index1 = pd.date_range(start='2014-06-01 00:00:00',
end='2014-06-01 00:15:00', freq='15S')
data1 = np.random.rand(len(index1))
df1 = pd.DataFrame(data=data1, index=index1, columns=['DF1'])
# plot df0 and df1:
fig, ax1 = plt.subplots(figsize=(40, 10))
ax = df0.plot.line(color="r")
df1.plot.bar(color='b', linewidth=5, ax=ax, alpha=0.7)
plt.show()
来源:https://stackoverflow.com/questions/60608914/plot-dataframe-overlay-line-and-bar-plot-doesnt-work-for-time-series-index