1

Good morning,

I have a small problem with subplotting using bar catplot of seaborn

here is a small example to illustrate:

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

y = [1.0, 5.5, 2.2, 9.8]
x = ["A", "B", "A", "B"]
z = ["type1", "type2", "type1", "type2"]

df = pd.DataFrame(x, columns=["x"])

df["y"] = y
df["z"] = z

print(df)

sns.catplot(x="x", y="y", data=df, col="z", kind="bar")
plt.show()

my problem is I want that the entries in the x axis that have 0.0 in the y axis , should not appear. Is there a way to do it? because the real example is more complex than this. I have at least 10 entries in the x axis (5 in each "type" and I want to strictly separate them but at the same time i want the bar graphs to be next to each other), it would look ugly otherwise.

here is the resulting image of the code enter image description here

thank you if you have any tips

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Josh.h
  • 71
  • 1
  • 13
  • Do you want to group A and B on the x-axis in a single plot, rather than in subplots? – r-beginners Oct 25 '21 at 07:35
  • if one plot cannot be a solution, than i dont mind having subplots. but with catplot it is not possible to do that. what would be an equivalent of this in matplotlib? – Josh.h Oct 25 '21 at 07:48
  • Try to code it with your data as I think it will be grouped into one graph. `sns.catplot(x="x", y="y", hue='z', kind="bar", data=df)` – r-beginners Oct 25 '21 at 07:50
  • i am sorry. may be i did not explain it well enough. i dont want to have them on the same graph. i want them separated in two plots just like the picture i posted but i dont want empty abcisses to be shown – Josh.h Oct 25 '21 at 07:52

1 Answers1

3

By default, the x-axes are shared. You can set sharex=False to prevent that.

I extended the example data a bit to make clear how the coloring works.

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

y = [1.0, 5.5, 2.2, 9.8, 3, 4]
x = ["A", "B", "A", "B", "C", "A"]
z = ["type1", "type2", "type1", "type2", "type1", "type2"]
df = pd.DataFrame({"x": x, "y": y, "z": z})

sns.catplot(x="x", y="y", data=df, col="z", kind="bar", sharex=False)

catplot with sharex=False

Note that this generates a warning (I'm testing with Seaborn 0.11.2):

UserWarning: Setting sharex=False with color=None may cause different levels of the x variable to share colors. This will change in a future version.

This means that the subplots are generated independently, which might make the coloring confusing. In the example, the "A" bar is blue in the first subplot, and orange in the second. You can work around this by using the "x" also for the "hue", leading to consistent colors. In that case, dodge=False will put just one bar per x-position.

sns.catplot(x="x", y="y", data=df, col="z", kind="bar", sharex=False, hue="x", dodge=False)

catplot with sharex=False and using hue=x

JohanC
  • 71,591
  • 8
  • 33
  • 66