How to plot horizontal lines (`hlines`) in a plot with category axis in `matplotlib.pyplot`?

Viewed 144

TLDR: I can use Axes.hlines(y, x1, x2) to plot horizontal lines on numerical axes, how do I do it on categorical axes?

My goal is to create horizontal lines, centered on category (string) values (e.g. 'a', ...) and extending 50% of the width between the categories on either side.


More detail

Consider the following 2 pandas.Series:

import pandas as pd
s1 = pd.Series([2, 2.5, -1, 3], pd.Index([6, 8, 10, 12], name='left-x')) # number index
s2 = pd.Series([2, 2.5, -1, 3], pd.Index(list('abcd'), name='x-value')) # str index

I can plot both as a bar graph with Axes.bar(x, y, width):

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2)
ax[0].bar(s1.index + 0.1, s1.values, width=1.8, align='edge') # width as numeric value
ax[1].bar(s2.index, s2.values, width=0.9) # width as fraction of distance between categories

enter image description here

But I cannot plot s2 as a hline graph with Axes.hlines(y, x1, x2)

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2)
ax[0].hlines(s1.values, s1.index, s1.index + 2)
ax[1].hlines(s2.values, ...) #<-- problem. s2.index is not numeric. What to do?

enter image description here

My goal is to create horizontal lines, centered on the index values ('a', ...) and extending 50% of the width between the categories on either side.

0 Answers
Related