I want to have a bar plot and a line plot on the same axis.
The line plot should be above the bars, colors should cycle as would be expected with two consecutive calls to plt.plot()
.
import matplotlib.pyplot as plt
import math
if __name__ == "__main__":
xs = range(1,10)
data = [0.3, 0.2, 0.1, 0.05, 0.05, 0.11, 0.09, 0.05, 0.07]
benfords = [math.log10(float(d 1)/d) for d in xs]
plt.bar(xs, data, ec='black', label='Data1')
plt.plot(xs, benfords, linestyle='--', marker='o', label="Benford's")
plt.xlabel('Digit')
plt.ylabel('Frequency')
plt.legend()
plt.show()
This code generates this:
Also adding zorder=1
and zorder=2
(or with any two consecutive numbers like 3 and 4 etc.) doesn't help.
When bar
is replaced with plot
two line plot of different colors appear as expected.
Python version: 2.7.8 Matplotlib version: 2.2.5 OS: Windows 10 x64
CodePudding user response:
Of course you can explicitly specify the color of each different set of bars, or of each line, but if you want to mix in the same axes bars and lines whose colors (and optionally other properties) obey a single, shared cycle, you must instantiate an appropriate itertools.cycle
object by calling the axes prop_cycle
In [16]: fig, ax = plt.subplots()
...: pc = plt.rcParams['axes.prop_cycle']() # we CALL the prop_cycle
...: npc = lambda: next(pc)
...: ax.bar((1,2,3), (5,4,6), label='b1', **npc())
...: ax.bar((1,2,3), (2,3,2), label='b2', **npc())
...: ax.plot((1,2,3),(9,6,8), label='l1', **npc())
...: ax.plot((1,2,3),(6,8,7), label='l2', **npc())
...: plt.legend()
...: plt.show()