Search code examples
pythonpandasmatplotlibseabornbar-chart

How can I make a barplot and a lineplot in the same plot with different Y axes?


I have two different sets of data with a common index, and I want to represent the first one as a barplot and the second one as a lineplot in the same graph. My current approach is similar to the following.

ax = pt.a.plot(alpha = .75, kind = 'bar')
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), pt.b.values, alpha = .75, color = 'r')

And the result is similar to this

A barplot and lineplot of the same data

This image is really nice and almost right. My only problem is that ax.twinx() seems to create a new canvas on top of the previous one, and the white lines are clearly seen on top of the barplot.

Is there any way to plot this without including the white lines?


Solution

  • You have to remove grid lines of the second axis. Add to the code ax2.grid(False). However y-ticks of the second axis will be not align to y-ticks of the first y-axis, like here:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import numpy as np
    import pandas as pd
    
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax1.plot(pd.Series(np.random.uniform(0,1,size=10)), color='g')
    ax2 = ax1.twinx()
    ax2.plot(pd.Series(np.random.uniform(0,17,size=10)), color='r')
    ax2.grid(False)
    plt.show()
    

    enter image description here