Matplotlib: Remove x-axis marks when ticks have been moved to top?

Viewed 35

I'm trying to make a plot grid on my Jupyter Notebook using Matplotlib. The plot grid has 9 rows x 3 columns, where the x-axis displays time (more specifically: years 2020-2022).

I would like the final plot grid to only show the labels on the top 3 plots (the first row). I succeeded on this, but now I have some ticks that I can't remove.

This is my code:

# Set size and general parameters for plots
plt.figure(figsize=(15, 40))
plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=.2, hspace=.2)
plt.rcParams["xtick.top"] = plt.rcParams["xtick.labeltop"] = True
plt.rcParams["xtick.bottom"] = plt.rcParams["xtick.labelbottom"] = False
plt.tick_params(left=False, right=False, top=False, bottom=False)

# Create lists to loop over the subplots
metrics = ["num_casos", "num_hosp", "num_def"]
max_y_vals = [.071, .0071, .0036]
y_steps = [.01, .001, .0005]

# Iterate over the lists above to create the necessary plots
for column, metric, max_y_val, y_step in zip([1, 2, 3], metrics, max_y_vals, y_steps):
    
    # Iterate over age groups and proper numbers to display each age group metric in the same row
    for age_group, i in zip(prop_dfs[metric].columns, range(column, 28, 3)):
        
        # Plot the evolution of the proportion of COVID-19 cases for each age groups
        plt.subplot(9, 3, i)
        prop_dfs[metric].loc[:, age_group].plot(kind='line', color="red")

        # Set axis parameters
        plt.ylim(0, max_y_val)
        plt.yticks(ticks=np.arange(0, max_y_val, y_step))
        plt.xlabel("")
        plt.xticks([0, 12, 24], labels=[2020, 2021, 2022])
                     
        # Set specific subplot parameters so only some of them show titles or labels
        if i == 1:
            plt.title("p(cases)", fontsize="18", fontweight="bold")
        if i == 2:
            plt.title("p(hospitalizations)", fontsize="18", fontweight="bold")
            plt.text(10, .01, "\nEvolution of the proportion of COVID-19 cases, hospitalizations\nand deaths from Spanish census across age groups\n",
                     color="black", horizontalalignment="center", verticalalignment="center", fontsize="28", fontweight="bold")
        if i == 3:
            plt.title("p(deaths)", fontsize="18", fontweight="bold")
        if i in range(1, 28, 3):
            plt.ylabel(age_group, fontsize="18", fontweight="bold")
        if i >= 4:
            plt.xticks([0, 12, 24], labels=[])

# Display the plots
plt.show()

And this is the output it produces (you'll notice the black ticks that clearly don't fit with the general style of the plot).

I would appreciate if someone can help me remove those ticks.

Best regards,

0 Answers
Related