Как изменить размер двойной оси matplotlibPython

Программы на Python
Anonymous
Как изменить размер двойной оси matplotlib

Сообщение Anonymous »

Я пытаюсь наложить две фигуры на графике, но когда я использую оси близнецов в качестве по умолчанию, полученный график не имеет большого смысла. Мне нужно переместить вторую фигуру (такую, которая будет наложена) в верхнюю часть первого графика. Как я могу отрегулировать ось Y, чтобы она также перемещалась на вершину, не теряя информацию, гарантируя, что значения графика все еще правильно соответствовали реальным данным? < /P>
< img alt = "Введите описание изображения здесь" src = "https://i.sstatic.net/tmp51lcj.png"/>
Ниже мой код, который включает в себя синтетические данные: < /p>
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Sample data for demonstration
np.random.seed(42)
dates = pd.date_range(start='2023-01-01', periods=50, freq='D')
precipitation_values = np.random.randint(0, 100, size=50)
precipitacao = pd.DataFrame({'Data Hora': dates, 'Precipitacao Total(mm)': precipitation_values})

y_fake = np.arange(precipitacao.shape[0])

# Define the figure size
fig, ax = plt.subplots(figsize=(12, 8)) # Larger figsize for added space around the plot area

# Sample line plot
ax.plot(precipitacao['Data Hora'], y_fake, label='Example Line')

# Customize labels and ticks
ax.set_xlabel('X-axis Label', fontsize=12)
ax.set_ylabel('Y-axis Label', fontsize=12)
ax.set_title('Plot Title', fontsize=14)

# Twin axis for precipitation
ax2 = ax.twinx()

# Define new precipitation axis limits to make bars occupy only the upper half
precip_max = precipitacao['Precipitacao Total(mm)'].max()
offset = 75
ax2.set_ylim(0, precip_max) # Keep the same scale but shift position

# Shift the bars up by adding an offset equal to half of the plot height
ax2.bar(precipitacao['Data Hora'], precipitacao['Precipitacao Total(mm)'],
color='blue', linewidth=1, alpha=0.5, zorder=12, bottom=offset)

# Adjust tick positions and labels
ax2.set_yticks(np.linspace(0, precip_max, 5)) # Define ticks only for the upper half
ax2.set_yticklabels([f"{int(tick)}" for tick in np.linspace(0, precip_max, 5)])

# Remove lower part of twin y-axis to avoid clutter
ax2.spines['bottom'].set_visible(False)
ax2.spines['right'].set_visible(True) # Keep right spine for precipitation
ax2.set_ylabel('Precipitação Total (mm)', fontsize=10)

# Place the legend outside of the plot area
legend = ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.3), ncol=3, fontsize=10)

# Adjust the subplots to ensure there's enough space for the legend
plt.subplots_adjust(top=0.9, bottom=0.2)

# Show the plot
plt.show()


Подробнее здесь: https://stackoverflow.com/questions/793 ... matplotlib

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