使用matplotlib add_gridspec时如何移除图表的小数刻度线与标签
Looks like you're hitting the default behavior of Seaborn's heatmap—it places y-axis ticks right in the middle of each cell, which leads to those annoying decimal values (like 0.5, 1.5, etc.). Here are two straightforward fixes depending on what you need:
Option 1: Hide Y-Ticks Entirely
If you don’t need any y-axis tick labels at all, just add one line inside your loop to turn them off:
for axi in axis: n = axis.index(axi) axi.set_title(str(names[n])) axi.set(xticklabels=[]) axi.set_xlabel('') axi.xaxis.set_visible(False) # Add this line to hide y-tick labels axi.set(yticklabels=[]) # Rest of your existing code for vlines and labels...
You can also use axi.yaxis.set_ticklabels([]) for the same effect—it’s just a matter of preference.
Option 2: Replace Decimals with Meaningful Labels
If you want to keep clean, readable y-ticks (like your dataframe’s row indices or sequential integers), adjust the ticks manually. First, make sure you have numpy imported (import numpy as np), then modify your loop to target each heatmap’s corresponding dataframe:
# Add a list linking each axis to its dataframe datasets = [df1, df2, df3, df4] for idx, axi in enumerate(axis): axi.set_title(names[idx]) axi.set(xticklabels=[]) axi.set_xlabel('') axi.xaxis.set_visible(False) # Grab the dataframe associated with this axis current_df = datasets[idx] # Set tick positions to the center of each row axi.set_yticks(np.arange(len(current_df)) + 0.5) # Use the dataframe's row indices as tick labels axi.set_yticklabels(current_df.index) # OR use sequential integers if you prefer: # axi.set_yticklabels(range(1, len(current_df)+1)) # Rest of your existing code for vlines and labels... h = axi.get_yticks() w = axi.get_xticks() axi.vlines(25, h[0] - 0.5, h[-1] + .5, linewidth=1, color="black") axi.vlines(50,h[0]-0.5,h[-1]+.5, linewidth=1, color="black") axi.vlines(75,h[0]-0.5,h[-1]+.5, linewidth=1, color="black") axi.vlines(100,h[0]-0.5,h[-1]+.5, linewidth=2, color="black") axi.set_ylabel('')
This works because we’re explicitly setting tick positions to match each cell’s center, then attaching labels that make sense (either your actual row data or clean integers) instead of the default decimal values.
内容的提问来源于stack exchange,提问作者SOK

