Код: Выделить всё
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.colors as c
from matplotlib.patches import Patch
from matplotlib.ticker import FixedLocator
data = {
'Sample1 stateA': np.random.randint(1, 11, 5),
'Sample1 stateB': np.random.randint(1, 11, 5),
'Sample1 stateC': np.random.randint(1, 11, 5),
'Sample2 stateA': np.random.randint(1, 11, 5),
'Sample2 stateB': np.random.randint(1, 11, 5),
'Sample2 stateC': np.random.randint(1, 11, 5),
}
# Create the DataFrame
df = pd.DataFrame(data)
# Plot
plt.figure(figsize=(12, 8))
ax = sns.heatmap(data
cbar=False,
linewidths=0.1,
linecolor='black',
annot=False,
vmin=1,
vmax=10
)
Нижние метки:
Код: Выделить всё
xticks_labels = []
for i, label in enumerate(data.columns):
# Split sample name and condition
sample_name, condition = label.split(' ', 1)
xticks_labels.append(condition) # Only show condition name on the heatmap top
# Set the xticks to show the condition
ax.set_xticklabels(xticks_labels, rotation=90)
Код: Выделить всё
# Set the ticks for the sample
# Get the sample names in the order of the sample columns
# Create a secondary x-axis for the sample names
ax2 = ax.twiny()
sample_names = [item.split(" ")[0] for item in data.columns]
ax2.yaxis.tick_left()
ticks = []
labels = []
prev_label = None
for i, label in enumerate(sample_names):
if label != prev_label:
ticks.append(i)
labels.append(label)
prev_label = label
ticks.append(i + 1)
ax2.xaxis.set_minor_locator(FixedLocator(ticks))
ax2.xaxis.set_major_locator(FixedLocator([(t0 + t1) / 2 for t0, t1 in zip(ticks[:-1], ticks[1:])]))
ax2.set_xticklabels(labels, rotation=0)
ax2.tick_params(axis='both', which='major', length=0)
ax2.tick_params(axis='x', which='minor', length=60)
# Show ax2 on top so it doesn't get hidden
ax2.spines['top'].set_position(('outward', 40))
# Adjust the layout to make sure both sets of labels are visible
plt.tight_layout()
# Save the plot to a file
plt.savefig(heatmap_file, dpi=300, bbox_inches='tight')
Если я попытаюсь создать верхние метки, используя одну и ту же ось (используя ax вместо ax2, я увижу верхние метки, но не нижнюю):
Код: Выделить всё
ax.yaxis.tick_left()
ticks = []
labels = []
prev_label = None
for i, label in enumerate(sample_names):
if label != prev_label:
ticks.append(i)
labels.append(label)
prev_label = label
ticks.append(i + 1)
ax.xaxis.set_minor_locator(FixedLocator(ticks))
ax.xaxis.set_major_locator(FixedLocator([(t0 + t1) / 2 for t0, t1 in zip(ticks[:-1], ticks[1:])]))
ax.set_xticklabels(labels, rotation=0)
ax.tick_params(axis='both', which='major', length=0)
ax.tick_params(axis='x', which='minor', length=60)
# Show ax2 on top so it doesn't get hidden
ax.spines['top'].set_position(('outward', 40))
# Adjust the layout to make sure both sets of labels are visible
plt.tight_layout()

Спасибо.
Подробнее здесь: https://stackoverflow.com/questions/789 ... and-bottom