Matplotlib/Seaborn — разные метки x сверху и снизуPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Matplotlib/Seaborn — разные метки x сверху и снизу

Сообщение Anonymous »

Я делаю сюжет, используя Python Seaborn:

Код: Выделить всё

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
)

Я хочу добавить разные метки сверху и снизу по оси X, примерно так:
Нижние метки:

Код: Выделить всё

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
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Matplotlib/Seaborn — разные метки x сверху и снизу
    Anonymous » » в форуме Python
    0 Ответы
    34 Просмотры
    Последнее сообщение Anonymous
  • Как удалить пробелы сверху и снизу диаграмм рассеяния Seaborn
    Anonymous » » в форуме Python
    0 Ответы
    12 Просмотры
    Последнее сообщение Anonymous
  • Как удалить пробелы сверху и снизу диаграмм рассеяния Seaborn
    Anonymous » » в форуме Python
    0 Ответы
    8 Просмотры
    Последнее сообщение Anonymous
  • Как создать коробку с двумя разными изображениями (одного размера) сверху и снизу?
    Anonymous » » в форуме JAVA
    0 Ответы
    104 Просмотры
    Последнее сообщение Anonymous
  • Заполнение прокрутки WKWebView сверху и снизу
    Гость » » в форуме IOS
    0 Ответы
    63 Просмотры
    Последнее сообщение Гость

Вернуться в «Python»