Python making combined bar and line plot with secondary y-axis
Solution 1:
Unfortunately it seems impossible to plot a bar plot and a lineplot to the same axes in pandas if the x axis is a dates axis.
A workaround is to use a matplotlib barplot instead
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("data.csv", index_col="DateTime", parse_dates=True, delim_whitespace=True)
fig, ax= plt.subplots()
ax.plot_date(df.index, df.iloc[:,11], '-')
for i in range(10):
diff = df.index[1]-df.index[0]
spacing = diff/(1.3*len(df.columns))
ax.bar(df.index+(-5+i)*spacing, df.iloc[:,i],
width=spacing/diff, label=df.columns[i])
plt.legend()
plt.gcf().autofmt_xdate()
plt.show()
Edit:
It will be possible to plot the bar plot and line plot in the same axes, if we neglect the fact that the points are dates. In the following code mind that we do not read the first column as index.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("data.csv", parse_dates=True, delim_whitespace=True)
ax = df.iloc[:,[0,1,2,3,4,5,6,7,8,9,10,11]].plot(kind='bar')
df.iloc[:,12].plot(linestyle='-', marker='o', ax = ax)
ax.set_xticklabels(df.DateTime, rotation=40)
plt.show()
So this method will produce a graph where the bars and linepoints are simply ordered by their index (which is not the date). This may be acceptable or not depending on whether the dates are equally spaced.
If we e.g. change the input file to skip a date (11/6/2014 is not present), the code will produce
where the bars and line points are still equally spaced, although the dates in reality are not.
Plotting the same data with one day skipped with the matplotlib code from the start of the answer we get
where indeed the 11/6/2014 is missing.