matplotlib modify outer x label and keep inner x label

Question:

I have a plot with 2 x_labels for two subplots. The inner x label is "Bronx, Brooklyn, Manhanttan, Queens, Staten Island"(or is it call x tick?), the outer x label is "borough":

Original plot

I want to find two different solutions to handle the "borough" labels.

  1. Remove both "borough" label from the graph.
  2. Keep 1 "borough" in the center of the two subplots.

The sample data is follow:

borough total_person_injured total_person_killed
QUEENS 1000 1000
QUEENS 2000 2000
BROOKLYN 1000 1000
BRONX 1000 1000
MANHATTAN 1000 1000
STATEN ISLAND 1000 1000

The code to generate the original plot is

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

df = pd.read_csv ("C:/file.csv")

fig, ax = plt.subplots (1,2)
plt.suptitle ("Collision injured verus killed per boroughs")

df_injured_killed = df.groupby ("borough")[["total_person_injured", "total_person_killed"]].sum()

ax[0].set_xticklabels (labels = df_injured_killed.index, rotation = 45)
ax[1].set_xticklabels (labels = df_injured_killed.index, rotation = 45)

# Future code will be add here

sb.barplot (x = df_injured_killed.index, y = df_injured_killed["total_person_injured"], ax = ax[0])
sb.barplot (x = df_injured_killed.index, y = df_injured_killed["total_person_killed"], ax = ax[1])

I had tried

ax[0].set_xlabel("")
ax[1].set_xlabel("")

and

ax[0].set(xlabel=None)
ax[1].set(xlabel=None)

and

fig, ax = plt.subplots (1,2, sharex=True)

Which had no effect on the graph.

I had tried

plt.axis("off")

Which remove inner and outer x labels for the right subplots:
Missing x label on right subplot

I had tried

ax1 = plt.axes()
x_axis = ax1.axes.get_xaxis()
x_axis.set_visible(False)

Which completely remove the graph from the plot:

Missing graph plot

I had tried

fig.text(0.5,0.001,"Borough",ha="center")

Which add more label:

More label plot

Asked By: xiaochuan fang

||

Answers:

Seaborn’s barplot returns an axis-object, you just need to assign it to a variable and then use set to remove it.

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

df = pd.read_csv ("C:/file.csv")

fig, ax = plt.subplots(1, 2)
plt.suptitle("Collision injured verus killed per boroughs")

df_injured_killed = df.groupby("borough")[["total_person_injured", "total_person_killed"]].sum()

ax[0].set_xticklabels(labels=df_injured_killed.index, rotation=45)
ax[1].set_xticklabels(labels=df_injured_killed.index, rotation=45)

# Future code will be add here

plot1 = sb.barplot(x=df_injured_killed.index, y=df_injured_killed["total_person_injured"], ax=ax[0])
plot2 = sb.barplot(x=df_injured_killed.index, y=df_injured_killed["total_person_killed"], ax=ax[1])

plot1.set(xlabel="")
plot2.set(xlabel="")
fig.text(0.5, -0.15, "Borough", ha="center")

I also added sharey=True to subplots which makes it look a bit cleaner.

Answered By: Rabinzel