I have a graph with, say, three lines. The red and blue lines have short labels, and the black dotted line has a longer more detailed label. Currently I have some code to produce the figure below.
import numpy as np
import matplotlib.pyplot as plt
a = np.linspace(0,50,20)
b = np.exp(-0.1*a)*70 np.random.random(20)*10
c = np.exp(-0.1*a)*70 np.random.random(20)*10
plt.plot(a,b,'b.-',lw=3,ms=10,label='short label')
plt.plot(a,c,'r.-',lw=3,ms=10,label='short label')
plt.plot([a[3],a[3]],[-1,100],'k--',lw=2,label='much longer label, I want to span two columns')
plt.ylim([0,80])
plt.xlim([0,50])
plt.legend(loc='best')
plt.show()
I would like to move the label for the red line so that it fills the space next to the label for the blue line (see figure below). Is this possible? Note I don't want the label for the black line to shrink and have a line-break.
CodePudding user response:
it can be done something like this
import numpy as np
import matplotlib.pyplot as plt
a = np.linspace(0,50,20)
b = np.exp(-0.1*a)*70 np.random.random(20)*10
c = np.exp(-0.1*a)*70 np.random.random(20)*10
plt.plot(a,b,'b.-',lw=3,ms=10,label='short label')
plt.plot([a[3],a[3]],[-1,100],'k--',lw=2,label='much longer label, I want to span two columns')
plt.plot(a,c,'r.-',lw=3,ms=10,label='short label')
plt.ylim([0,80])
plt.xlim([0,50])
plt.legend(loc='best', ncol=2,columnspacing=-8)
plt.show()
You can reduce the size between the columns more by reducing the value of columnspacing, but the frame of legend will also reduce. Your third label will go outside the frame as its length is larger.
CodePudding user response:
One option is to add the argument column to the function legend:
import numpy as np
import matplotlib.pyplot as plt
a = np.linspace(0,50,20)
b = np.exp(-0.1*a)*70 np.random.random(20)*10
c = np.exp(-0.1*a)*70 np.random.random(20)*10
plt.plot(a,b,'b.-',lw=3,ms=10,label='short label')
plt.plot([a[3],a[3]],[-1,100],'k--',lw=2,label='much longer label, I want to span two columns')
plt.plot(a,c,'r.-',lw=3,ms=10,label='short label')
plt.ylim([0,80])
plt.xlim([0,50])
plt.legend(loc='best', ncol = 2)
plt.show()