Python making combined bar and line plot with secondary y-axis

后端 未结 2 1838
暗喜
暗喜 2020-12-02 01:05

I am trying to plot some csv data. I would like to plot some csv data. The data is shown below. I\'m trying to plot columns 1-11 as a bar plot and column 12 as a line. I

相关标签:
2条回答
  • 2020-12-02 01:39

    You just need to plot them on the same axis

    ax = df.iloc[:,[0,1,2,3,4,5,6,7,8,9,10]].plot(kind='bar')
    df.iloc[:,12].plot(linestyle='-', marker='o', ax = ax)
    
    ax.set_xticklabels(df.DateTime, rotation=40) #set the x-ticks to datetime column and rotate
    

    is the code I used to plot both the graphs on same plot

    0 讨论(0)
  • 2020-12-02 01:41

    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.

    0 讨论(0)
提交回复
热议问题