seaborn barplot add xticks for hue

Viewed 3861

Seaborn barplots have an xtick for every unique value along the x coordinate. But for the hue values, there are no ticks:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame(columns=["model", "time", "value"])
df["model"] = ["on"]*2 + ["off"]*2
df["time"] = ["short", "long"] * 2
df["value"] = [1, 10, 2, 4]

fig, ax = plt.subplots()
bar = sns.barplot(data=df, x="model", hue="time", y="value", edgecolor="white")

barplots

Is it possible to add ticks for the hue, too? Some of the hue colors are quite similar and I would like to add a text description, too.

1 Answers

You have to be careful about the number of hues that you might have in your dataset, and the number of categories and so forth. If you have N categories, then they are each plotted at axis coordinates 0,1,...,N-1. Then the various hues are plotted centered around this coordinate. For 2 hues like in your example, the bars are at x±0.2

fig, ax = plt.subplots()
bar = sns.barplot(data=df, x="model", hue="time", y="value", edgecolor="white")
ax.set_xticks([-0.2,0.2, 0.8,1.2])
ax.set_xticklabels(["on/short","on/long",'off/short','off/long'])

enter image description here

Note that I would strongly recommend that you use order= and hue_order= in your call to barplot() to be sure that your labels match the bars.

Related