最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to resize twin axis matplotlib - Stack Overflow

programmeradmin1浏览0评论

I'm trying to overlay two figures in a plot, but when I use the twin axes as default, the resulting plot doesn't make much sense. I need to move the second figure (the one to be overlaid) to the top of the first graph. How can I adjust the y-axis so that it also moves to the top, without losing the information, ensuring that the values of the bar plot still correspond correctly to the real data?

Below is my code, which includes synthetic data:

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()
发布评论

评论列表(0)

  1. 暂无评论