更改等高线clabel文本对象的方向

2024-06-09 00:47:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python Matplotlib绘制等高线。下面是一些代码作为基础。如果你运行这个,你会看到标签几乎是垂直的。我想让标签的方向水平,但我不知道如何才能做到这一点。我尝试过使用ClabelText,文档中建议这样做,但不明白这是如何工作的。如果有人能建议一种方法来确定标签的方向,我将不胜感激。在

import itertools as it
import numpy as np
from matplotlib.ticker import FuncFormatter
from matplotlib.contour import ClabelText
import matplotlib.pyplot as plt
from math import pi, log 

def getTime(data):
    M = data['weight']
    Tei  = data['temp']
    Twasser = 99.8
    Teikl = 86.0  ## max allowed temp
    k = 0.262 ## estimate was 0.3 W/(m.K),
    Crho = 3.18 # (KJ/kgC)
    const = pow(Crho, 1.0/3) / (pi*pi*k*pow(4*pi/3,2.0/3))
    Tval = const*pow(M,2.0/3)*log(0.76*(Tei-Twasser)/(Teikl-Twasser))
    return Tval # coo time in minutes

def contourFmt(val, posn):
    mins = int(val // 1)
    secs = int(val % 1 *60)
    return '{0:d}mm{1:d}ss'.format(mins, secs)

def labeler(val): #is this any use??
    print(val)
    return

#weights = np.array(range(40, 80, 5))*1.0
#temps = np.array(range(0, 30, 5))*1.0
weights = np.arange(40.0, 80.0, 5.0)
temps = np.arange(0.0, 25.01, 5.0)

X = temps
Y = weights
Z = np.zeros((len(X), len(Y))) 
xx = [{'temp':i} for i in X]
yy = [{'weight':i} for i in Y]
plt.figure()

##zz = it.product(xx,yy)

for i, xdicts in enumerate(xx):
    for j, ydicts in enumerate(yy):
        zd = {}
        zd.update(xdicts)
        zd.update(ydicts)
        zval = getTime(zd)
        Z[i,j] = zval

times = np.arange(4.00, 6.50, 0.25)
CS = plt.contour(Y, X, Z, levels=times, colors='b')

lbl = ClabelText(labeler)
lbl.set_rotation('horizontal')
formatter = FuncFormatter(contourFmt)  
#plt.clabel(CS, inline=True, fmt=formatter, fontsize=12)
plt.clabel(CS, inline=True, use_clabeltext=True, fmt=formatter, fontsize=12)

plt.grid(True)
plt.clabel(CS, inline=1, fontsize=12)
plt.show()

Tags: infromimporttrueformatplotlibasnp
1条回答
网友
1楼 · 发布于 2024-06-09 00:47:59

可以在设置单个标签的旋转之后创建这些标签。标签Text对象是由clabel返回的,因此您可以存储它们并对其进行迭代,使用.set_rotation(0)来水平定位它们。在

将脚本的最后几行更改为:

labels1 = plt.clabel(CS, inline=True, use_clabeltext=True, fmt=formatter, fontsize=12)
labels2 = plt.clabel(CS, inline=1, fontsize=12)

for l in labels1+labels2:
    l.set_rotation(0)

enter image description here

相关问题 更多 >