本文介绍了使用matplotlib仅显示一个子图的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 matplotlib 以正确格式显示图例时遇到问题.

I'm facing a problem in showing the legend in the correct format using matplotlib.

我在一个图形中有2个2比2的4个子图,我只想在第一个子图上画图,该图上画了两行.我使用下面随附的代码获得的图例包含无尽的条目,并在整个图中垂直延伸.当我使用 linspace 使用相同的代码生成假数据时,图例工作得非常好.

I have 4 subplots in a figure in 2 by 2 format and I want legend only on the first subplot which has two lines plotted on it. The legend that I got using the code attached below contained endless entries and extended vertically throughout the figure. When I use the same code using linspace to generate fake data the legend works absolutely fine.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import os

#------------------set default directory, import data and create column output vectors---------------------------#

path="C:/Users/Pacman/Data files"
os.chdir(path)
data =np.genfromtxt('vrp.txt')

x=np.array([data[:,][:,0]])

y1=np.array([data[:,][:,6]])
y2=np.array([data[:,][:,7]])
y3=np.array([data[:,][:,9]])
y4=np.array([data[:,][:,11]])
y5=np.array([data[:,][:,10]])

nrows=2
ncols=2
tick_l=6   #length of ticks
fs_axis=16 #font size of axis labels


plt.rcParams['axes.linewidth'] = 2         #Sets global line width of all the axis
plt.rcParams['xtick.labelsize']=14         #Sets global font size for x-axis labels
plt.rcParams['ytick.labelsize']=14         #Sets global font size for y-axis labels



plt.subplot(nrows, ncols, 1)

ax=plt.subplot(nrows, ncols, 1)
l1=plt.plot(x, y2, 'yo',label='Flow rate-fan')
l2=plt.plot(x,y3,'ro',label='Flow rate-discharge')
plt.title('(a)')
plt.ylabel('Flow rate ($m^3 s^{-1}$)',fontsize=fs_axis)
plt.xlabel('Rupture Position (ft)',fontsize=fs_axis)

# This part is not working
plt.legend(loc='upper right', fontsize='x-large')

#Same code for rest of the subplots

我尝试实施以下链接中建议的修复程序,但是无法使其工作:我如何为matplotlib 有很多子图?

I tried to implement a fix suggested in the following link, however, could not make it work:how do I make a single legend for many subplots with matplotlib?

在这方面的任何帮助将不胜感激.

Any help in this regard will be highly appreciated.

推荐答案

在处理子图时,直接使用轴(在您的情况下为 ax )非常有用.因此,如果您在一个图中设置了两个图并且只希望在第二个图中有一个图例:

It is useful to work with the axes directly (ax in your case) when when working with subplots. So if you set up two plots in a figure and only wish to have a legend in your second plot:

t = np.linspace(0, 10, 100)

plt.figure()

ax1 = plt.subplot(2, 1, 1)
ax1.plot(t, t * t)

ax2 = plt.subplot(2, 1, 2)
ax2.plot(t, t * t * t)
ax2.legend('Cubic Function')

请注意,在创建图例时,我使用的是 ax2 而不是 plt .如果要为第一个子图创建第二个图例,则可以使用相同的方法,但要在 ax1 上进行.

Note that when creating the legend, I am doing so on ax2 as opposed to plt. If you wish to create a second legend for the first subplot, you can do so in the same way but on ax1.

这篇关于使用matplotlib仅显示一个子图的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:58