Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何减少等高线图图例中的小数量?_Python_Matplotlib_Legend - Fatal编程技术网

Python 如何减少等高线图图例中的小数量?

Python 如何减少等高线图图例中的小数量?,python,matplotlib,legend,Python,Matplotlib,Legend,我只想给图例取一个小数位。绘图所基于的数据(w_字段)具有8位小数的值 w_field = np.genfromtxt('w_field.dat') CV = plt.contour(w_field) x,Vel = CV.legend_elements() plt.legend(x,Vel, title= 'Vertical velocity (m/s)', fontsize= 10, bbox_to_anchor=(1.05, 1), loc='upper left') plt.xlab

我只想给图例取一个小数位。绘图所基于的数据(w_字段)具有8位小数的值

w_field = np.genfromtxt('w_field.dat') 
CV = plt.contour(w_field)
x,Vel = CV.legend_elements()
plt.legend(x,Vel, title= 'Vertical velocity (m/s)', fontsize= 10, bbox_to_anchor=(1.05, 1), loc='upper left') 
plt.xlabel('Nx')
plt.ylabel('Ny')

这应该行得通

fig, ax = plt.subplots()
w_field = np.genfromtxt('w_field.dat') 
CV = ax.contour(w_field)
x,Vel = CV.legend_elements()
plt.legend(x,Vel, title= 'Vertical velocity (m/s)', fontsize= 10, bbox_to_anchor=(1.05, 1), loc='upper left') 
plt.xlabel('Nx')
plt.ylabel('Ny')

leg = ax.get_legend()

for lbl in leg.get_texts():
    label_text = lbl.get_text()
    float_num = label_text.split()[2]
    new_text = f'X = {float(float_num):,.1f}'
    lbl.set_text(new_text)
该函数接受格式化参数,该参数应为返回格式化字符串的函数。下面是一个示例,显示了与默认格式的差异

从matplotlib导入pyplot作为plt
将numpy作为np导入
w_field=np.random.randn(60100).cumsum(轴=1).cumsum(轴=0)/50
CV=plt.轮廓(w_场)
x、 标高=CV.图例_元素()
legend1=plt.legend(x,Vel,title='Default formatting',fontsize=10,bbox_to_anchor=(1.02,1.02),loc='左上角')
x、 Vel=CV.legend\u元素(str\u格式=lambda x:f'{x:.1f}')
plt.legend(x,Vel,title='With formatting function',fontsize=10,bbox_to_anchor=(1.02,0),loc='左下角')
plt.gca().add_artist(legend1)#matplotlib在创建第二个图例时删除该图例,然后再次添加
plt.紧_布局()
plt.show()


PS:甚至连电视都会显示这种奇怪的格式。

这能回答你的问题吗@ZarakiKenpachi链接的解决方案不适合这种情况。第一种解决方案是填充轮廓。第二个使用了
clabel
,这不适用于短轮廓。答案很好!如果你像这样格式化字符串,它看起来更漂亮:
x,Vel=CV.legend\u elements(str\u format=lambda x:f'{x:.1f}')
@Scotty1-我一定在逃避什么。您只是在冒号后面添加了一个空格?这有区别吗?@JohanC Yep,它为正数引入了一个空格,这样正数和负数在第一位对齐。@Scotty1-好的,我不知道这个。谢谢不幸的是,它在这种情况下不起作用,因为
plt.contour
legend\u元素
强制进行TeX渲染,总是在数字周围添加
“$x=…$”
。此外,TeX减号比一个空格宽得多。哦,对了,不知何故,TeX渲染是错误的。现在,重新启动将复制您描述的行为。在这种情况下,用显式加号替换空白将使格式更好:<代码> x,VEL= cv.LeundEngEnter元素(StruthFrase= lambda x:f' {x:+1f})。不幸的是,我不知道有任何内置的TeX命令来生成正确大小的间距,而不是加号。在Latex中,我会使用SIunitx或align env。为此,但在matplotlib中实现它相当复杂。。。