[英]Matplotlib - set an axis label where there are no ticks
您好,Python / Matplotlib專家,
我想在繪制特定水平線的隨機點處標記y軸。
我的Y軸不應有任何值,而應僅顯示主要刻度線。
為了清楚說明我的要求,我將使用一些屏幕截圖。 我目前所擁有的: 我想要的是:
如您所見, E1和E2不在主刻度線上。 實際上,我知道y軸值(盡管應該將其隱藏,因為它是模型圖)。 我也知道E1和E2的值。
我將不勝感激。
讓我的代碼段如下所示:
ax3.axis([0,800,0,2500) #You can see that the major YTick-marks will be at 500 intervals
ax3.plot(x,y) #plot my lines
E1 = 1447
E2 = 2456
all_ticks = ax3.yaxis.get_all_ticks() #method that does not exist. If it did, I would be able to bind labels E1 and E2 to the respective values.
感謝您的幫助!
編輯:對於另一張圖,我使用此代碼為標簽設置了各種顏色。 這很好。 energy_range
, labels_energy
和colors_energy
是與y軸一樣大的numpy數組,在我的情況下為2500。
#Modify the labels and colors of the Power y-axis
for i, y in enumerate(energy_range):
if (i == int(math.floor(E1))):
labels_energy[i] = '$E_1$'
colors_energy[i] = 'blue'
elif (i == int(math.floor(E2))):
labels_energy[i] = '$E_2$'
colors_energy[i] = 'green'
else:
labels_energy.append('')
#Modify the colour of the energy y-axis ticks
for color,tick in zip(colors_energy,ax3.yaxis.get_major_ticks()):
print color, tick
if color:
print color
tick.label1.set_color(color) #set the color property
ax3.get_yaxis().set_ticklabels(labels_energy)
Edit2:具有虛擬值的完整樣本:
#!/bin/python
import matplotlib
# matplotlib.use('Agg') #Remote, block show()
import numpy as np
import pylab as pylab
from pylab import *
import math
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import matplotlib.font_manager as fm
from matplotlib.font_manager import FontProperties
import matplotlib.dates as mdates
from datetime import datetime
import matplotlib.cm as cm
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from scipy import interpolate
def plot_sketch():
x = np.arange(0,800,1)
energy_range = range (0,2500,1) #Power graph y-axis range
labels_energy = [''] * len(energy_range)
colors_energy = [''] * len(energy_range)
f1=4
P1=3
P2=2
P3=4
f2=2
f3=6
#Set Axes ranges
ax3.axis([0,800,0,energy_range[-1]])
#Add Energy lines; E=integral(P) dt
y=[i * P1 for i in x]
ax3.plot(x,y, color='b')
y = [i * P2 for i in x[:0.3*800]]
ax3.plot(x[:0.3*800],y, color='g')
last_val = y[-1]
y = [(i * P3 -last_val) for i in x[(0.3*800):(0.6*800)]]
ax3.plot(x[(0.3*800):(0.6*800)],y, color='g')
E1 = x[-1] * P1
E2 = (0.3 * x[-1]) * P2 + x[-1] * (0.6-0.3) * P3
#Modify the labels and colors of the Power y-axis
for i, y in enumerate(energy_range):
if (i == int(math.floor(E1))):
labels_energy[i] = '$E_1$'
colors_energy[i] = 'blue'
elif (i == int(math.floor(E2))):
labels_energy[i] = '$E_2$'
colors_energy[i] = 'green'
else:
labels_energy.append('')
#Modify the colour of the power y-axis ticks
for color,tick in zip(colors_energy,ax3.yaxis.get_major_ticks()):
if color:
tick.label1.set_color(color) #set the color property
ax3.get_yaxis().set_ticklabels(labels_energy)
ax3.axhline(energy_range[int(math.floor(E1))], xmin=0, xmax=1, linewidth=0.25, color='b', linestyle='--')
ax3.axhline(energy_range[int(math.floor(E2))], xmin=0, xmax=0.6, linewidth=0.25, color='g', linestyle='--')
#Show grid
ax3.xaxis.grid(True)
#fig = Sketch graph
fig = plt.figure(num=None, figsize=(14, 7), dpi=80, facecolor='w', edgecolor='k')
fig.canvas.set_window_title('Sketch graph')
ax3 = fig.add_subplot(111) #Energy plot
ax3.set_xlabel('Time (ms)', fontsize=12)
ax3.set_ylabel('Energy (J)', fontsize=12)
pylab.xlim(xmin=0) # start at 0
plot_sketch()
plt.subplots_adjust(hspace=0)
plt.show()
我認為你正在尋找正確的變換(檢查這出)。 在您的情況下,我想您想要的就是簡單地使用text
方法和正確的transform
kwarg。 嘗試在axhline調用之后將其添加到plot_sketch函數中:
ax3.text(0, energy_range[int(math.floor(E1))],
'E1', color='g',
ha='right',
va='center',
transform=ax3.get_yaxis_transform(),
)
ax3.text(0, energy_range[int(math.floor(E2))],
'E2', color='b',
ha='right',
va='center',
transform=ax3.get_yaxis_transform(),
)
get_yaxis_transform
方法返回一個“混合”變換,該變換使輸入到text
調用的x值以軸為單位繪制,y數據以“ data”為單位繪制。 您可以將x數據的值(0)調整為-0.003或如果您需要一點填充的值(或者可以使用ScaledTranslation
轉換,但通常是一次性的,則不需要)。
您可能還需要對set_ylabel使用'labelpad'選項,例如:
ax3.set_ylabel('Energy (J)', fontsize=12, labelpad=20)
我認為我對另一篇文章的回答可能對您有所幫助: Matplotlib:將字符串添加為自定義X-ticks,但還保留現有的(數字)刻度標簽? matplotlib.pyplot.annotate的替代品?
它也適用於y軸,結果如下:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.