python画图如何调整图例位置_Python-如何将图例排除在情节之外
小編典典
有很多方法可以做你想要的。要添加@inalis和@Navi所說的內容,可以使用bbox_to_anchor關鍵字參數將圖例部分地放置在軸外and/or 減小字體大小。
在考慮減小字體大小(這會使閱讀起來非常困難)之前,請嘗試將圖例放在不同的位置:
因此,讓我們從一個通用示例開始:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
ax.plot(x, i * x, label='$y = %ix$' % i)
ax.legend()
plt.show()
如果我們做同樣的事情,但是使用bbox_to_anchor關鍵字參數,我們可以將圖例稍微移出軸邊界:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
ax.plot(x, i * x, label='$y = %ix$' % i)
ax.legend(bbox_to_anchor=(1.1, 1.05))
plt.show()
同樣,你可以使圖例更加水平和/或將其放在圖的頂部(我也打開了圓角和簡單的陰影):
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
line, = ax.plot(x, i * x, label='$y = %ix$'%i)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
ncol=3, fancybox=True, shadow=True)
plt.show()
另外,你可以縮小當前圖的寬度,并將圖例完全放在圖的軸外:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
ax.plot(x, i * x, label='$y = %ix$'%i)
# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
# Put a legend to the right of the current axis
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()
同樣,你可以垂直縮小圖,并在底部放置水平圖例:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
for i in xrange(5):
line, = ax.plot(x, i * x, label='$y = %ix$'%i)
# Shrink current axis's height by 10% on the bottom
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1,
box.width, box.height * 0.9])
# Put a legend below current axis
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
fancybox=True, shadow=True, ncol=5)
plt.show()
2020-02-07
總結
以上是生活随笔為你收集整理的python画图如何调整图例位置_Python-如何将图例排除在情节之外的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [每日编程]求 largest Numb
- 下一篇: shape的简单用法