matplotlib 如何合并多个图表?

ovfsdjhp  于 2023-05-29  发布在  其他
关注(0)|答案(1)|浏览(130)

我有3个图表一个条形图和2皮棉图我怎么能合并他们在一起,得到一个图表而不干扰他们的个别属性
下面是我用来创建3个图表的代码

ax = plt.subplots()
# creating axes object and defining plot
ax1 = dataset.plot(kind = 'bar', x = 'month', y = 'max_temp', color = 'lightblue', secondary_y = True, linewidth = 3, alpha=0.5, legend=False)

ax2 = dataset.plot(kind = 'line', x = 'month', y = 'min_temp', color = 'green', linewidth = 3,  marker='o', markerfacecolor='white', markersize=12, legend=False)
ax3 = dataset.plot(kind = 'line', x = 'month', y = 'max_temp', color = 'blue', linewidth = 3,  marker='o', markerfacecolor='white', markersize=12, legend=False)

ax1.invert_yaxis()
ax2.fill_between(dataset['month'], dataset['min_temp'], color='lightgreen', alpha=0.5)
ax3.fill_between(dataset['month'], dataset['max_temp'], color='lightblue', alpha=0.5)
#title of the plot
plt.title("Daily Forecast", loc='left')

#labeling x and y-axis

ax2.set_ylabel('Temperature (Degree °C)', color = "black")
ax1.set_ylabel('Rainfall (mm)', color = 'black')

#defining display layout

# plt.legend( bbox_to_anchor=(1.05, 1.35), loc='upper right')

plt.savefig('file_name.jpg', dpi=400)
#show plot
plt.show()

从上面的代码中我得到的输出

我怎样才能将它们组合在一起,使我的单图表不干扰这些属性

ivqmmu1c

ivqmmu1c1#

IIUC,您可以用途:

fig, ax = plt.subplots(figsize=(6, 4))
ax2 = ax.twinx()  # to isolate the line plots

dataset.plot(kind='bar', x='month', y='rainfall',
             color='lightblue', ax=ax, width=0.4, legend=False)

ax.invert_yaxis()  # to invert the y-axis for the bar plot

ax2.plot(dataset['month'], dataset['min_temp'], color='green',
         linewidth=3, marker='o', markerfacecolor='white', markersize=12)

ax2.fill_between(dataset['month'], dataset['min_temp'], color='lightgreen', alpha=0.5)

ax2.plot(dataset['month'], dataset['max_temp'], color='blue',
         linewidth=3, marker='o', markerfacecolor='white', markersize=12)

ax2.fill_between(dataset['month'], dataset['max_temp'], color='lightblue', alpha=0.5)

ax.set_ylabel('Rainfall (mm)', color='black')
ax2.set_ylabel('Temperature (Degree °C)', color='black')

ax.set_title('Daily Forecast', loc='left')

ax.yaxis.tick_right()
ax.yaxis.set_label_position('right')

ax2.yaxis.tick_left()
ax2.yaxis.set_label_position('left')

plt.show();

输出:

  • 使用的输入:*
np.random.seed(123456)

dataset = pd.DataFrame(
    {'month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
     'max_temp': np.random.randint(25, 40, 5),
     'min_temp': np.random.randint(15, 25, 5),
     'rainfall': np.random.randint(30, 70, 5)}
)

相关问题