no handles with labels found to put in 本田legendd怎么办

python画图matplotlib的Legend(显示图中的标签)
legend(x, y = NULL, legend, fill = NULL, col = par("col"),
border ="black", lty, lwd, pch,
angle = 45,density = NULL, bty = "o", bg = par("bg"),
box.lwd = par("lwd"),box.lty = par("lty"), box.col = par("fg"),
pt.bg = NA, cex =1, pt.cex = cex, pt.lwd = lwd,
xjust = 0, yjust= 1, x.intersp = 1, y.intersp = 1,
adj = c(0, 0.5),text.width = NULL, text.col = par("col"),
text.font = NULL,merge = do.lines && has.pch, trace = FALSE,
plot = TRUE, ncol= 1, horiz = FALSE, title = NULL,
inset = 0, xpd,title.col = text.col, title.adj = 0.5,
seg.len = 2)
X,y用于定位图例,也可用单键词"bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right" and "center"
字符或表达式向量
用特定的颜色进行填充
图例中出现的点或线的颜色
当fill = 参数存在的情况下,填充色的边框
图例中线的类型与宽度
阴影的角度
阴影线的密度
图例框是否画出,o为画出,默认为n不画出
bty != "n"时,图例的背景色
box.lty, box.lwd, box.col
bty = "o"时,图例框的类型,box.lty决定是否为虚线,box.lwd决定粗线,box.col决定颜色
点的背景色
点的边缘的线宽
图例中文字离图片的水平距离
图例中文字离图片的垂直距离
图例中字体的相对位置
text.width
图例字体所占的宽度
图例字体的颜色
logical, if TRUE,合并点与线,但不填充图例框,默认为TRUE
if TRUE显示图例信息.
logical. If FALSE不画出图例
图例中分类的列数
if TRUE,水平放置图例
给图例加标题
当图例用关键词设置位置后,inset = 分数,可以设置其相对位置
xpd=FALSE,即不允许在作图区域外作图,改为TRUE即可,与par()参数配合使用。
图例标题的相对位置,0.5为默认,在中间。0最左,1为最右。
lty 与lwd的线长,长度单位为字符宽度
legend 显示图例
1 legend基础
函数原型 legend(*args,
当len(args)
args 是[artist]和[label]的集合
当len(args)
args会自动调用get_legend_handles_labels()生成
labels = ax.get_legend_handles_labels()
ax.legend(handles,
ax.get_legend_handles_labels()的作用在于返回ax.lines,
ax.patch所有对象以及ax.collection中的LineCollection or RegularPolyCollection对象
注意:这里只提供有限支持, 并不是所有的artist都可以被用作图例,比如errorbar支持不完善
1.1 调整顺序
ax = subplot(1,1,1)
p1, = ax.plot([1,2,3],
label="line 1")
p2, = ax.plot([3,2,1],
label="line 2")
p3, = ax.plot([2,3,1],
label="line 3")
handles, labels = ax.get_legend_handles_labels()
# reverse the order
ax.legend(handles[::-1], labels[::-1])
# or sort them by labels
import operator?hl = sorted(zip(handles, labels),
key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)
ax.legend(handles2, labels2)
1.2 使用代理artist
当需要使用legend不支持的artist时,可以使用另一个被legend支持的artist作为代理
比如以下示例中使用不在axe上的一个artist
p = Rectangle((0, 0),
1, 1, fc="r")
legend([p], ["Red Rectangle"])
2 多列图例
ax1 = plt.subplot(3,1,1)
ax1.plot([1],
label="multi\nline")
ax1.plot([1],
label="$2^{2^2}$")
ax1.plot([1],
label=r"$\frac{1}{2}\pi$")
ax1.legend(loc=1,
ncol=3, shadow=True)
ax2 = plt.subplot(3,1,2)
myplot(ax2)
ax2.legend(loc="center
left", bbox_to_anchor=[0.5, 0.5],
shadow=True, title="Legend")
ax2.get_legend().get_title().set_color("red")
3 图例位置
ax.legend(….,
loc=3) 具体对应位置如下图
绘制在图上是这样的,(具体没有分清 5和7的区别)
4 多个图例
如果不采取措施,连续调用两个legend会使得后面的legend覆盖前面的
from matplotlib.pyplot import * p1, = plot([1,2,3],
label="test1")
p2, = plot([3,2,1],
label="test2")
l1 = legend([p1],
["Label 1"], loc=1)?l2 = legend([p2], ["Label 2"], loc=4) #
this removes l1 from the axes.
gca().add_artist(l1) #
add l1 as a separate artist to the axes
matplotlib.legend.Legend(parent, handles, labels,**args)
三个最重要的必要参数
parent --- legend的父artist,
包含legend的对象
比如用ax.legend()调用之后
&&& print ax.get_legend().parent
Axes(0.125,0.1;0.775x0.8)
handles --- 图例上面画出的各个artist(lines,
labels --- artist 对应的标签
Description
a location code
the font property (matplotlib.font_manager.FontProperties 对象)
song_font = matplotlib.font_manager.FontProperties(fname='simsun.ttc', size=8)
the font size (和prop互斥,不可同时使用)
markerscale
the relative size of legend markers vs. original
the number of points in the legend for line
scatterpoints
the number of points in the legend for scatter plot
scatteryoffsets
a list of yoffsets for scatter symbols in legend
if True, draw a frame around the legend. If None, use rc
if True, draw a frame with a round fancybox. If None, use rc
if True, draw a shadow behind legend
number of columns
the fractional whitespace inside the legend border
labelspacing
the vertical space between the legend entries
handlelength
the length of the legend handles
handleheight
the length of the legend handles
handletextpad
the pad between the legend handle and text
borderaxespad
the pad between the axes and legend border
columnspacing
the spacing between columns
the legend title
bbox_to_anchor
the bbox that the legend will be anchored.
bbox_transform
the transform for the bbox. transAxes if None.
get_frame() ---
返回legend所在的方形对象
get_lines()
get_patches()
get_texts()
get_title() ---
上面几个比较简单,不解释了
set_bbox_to_anchor(bbox,
transform=None)
(…本函数待续…之后写axes的时候会加入,目前我没有看懂他的这个长宽和figure以及axes的关系)
leg = ax.legend(('Model
length', 'Data length', 'Total message length'),
center', shadow=True)
# the matplotlib.patches.Rectangle
instance surrounding the legend 即外框
= leg.get_frame()
frame.set_facecolor('0.80')
set the frame face color to light gray
# matplotlib.text.Text instances 即legend中文本
for t in leg.get_texts():
t.set_fontsize('small')
the legend text fontsize
# matplotlib.lines.Line2D
instances 即legend中所表示的artist
for l in leg.get_lines():
l.set_linewidth(1.5)
the legend line width
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.4, 0.7])
ax2 = fig.add_axes([0.55, 0.1, 0.4, 0.7])
x = np.arange(0.0, 2.0, 0.02)
y1 = np.sin(2*np.pi*x)
y2 = np.exp(-x)
l1, l2 = ax1.plot(x,
y1, 'rs-', x, y2, 'go')
y3 = np.sin(4*np.pi*x)
y4 = np.exp(-2*x)
l3, l4 = ax2.plot(x,
y3, 'yd-', x, y3, 'k^')
fig.legend((l1,
l2), ('Line 1', 'Line 2'), 'upper
fig.legend((l3,
l4), ('Line 3', 'Line 4'), 'upper
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])
plt.show()
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
blue_line = mlines.Line2D([], [], color='blue', marker='*',
markersize=15, label='Blue stars')
plt.legend(handles=[blue_line])
plt.show()
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
import matplotlib.pyplot as plt
line1, = plt.plot([1,2,3], label="Line 1", linestyle='--')
line2, = plt.plot([3,2,1], label="Line 2", linewidth=4)
# Create a legend for the first line.
first_legend = plt.legend(handles=[line1], loc=1)
# Add the legend manually to the current Axes.
ax = plt.gca().add_artist(first_legend)
# Create another legend for the second line.
plt.legend(handles=[line2], loc=4)
plt.show()
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
line1, = plt.plot([3,2,1], marker='o', label='Line 1')
line2, = plt.plot([1,2,3], marker='o', label='Line 2')
plt.legend(handler_map={line1: HandlerLine2D(numpoints=4)})
import matplotlib.pyplot as plt
from numpy.random import randn
z = randn(10)
red_dot, = plt.plot(z, "ro", markersize=15)
# Put a white cross over some of the data.
white_cross, = plt.plot(z[:5], "w+", markeredgewidth=3, markersize=15)
plt.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"])
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
class AnyObject(object):
class AnyObjectHandler(object):
def legend_artist(self, legend, orig_handle, fontsize, handlebox):
x0, y0 = handlebox.xdescent, handlebox.ydescent
width, height = handlebox.width, handlebox.height
patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red',
edgecolor='black', hatch='xx', lw=3,
transform=handlebox.get_transform())
handlebox.add_artist(patch)
return patch
plt.legend([AnyObject()], ['My first handler'],
handler_map={AnyObject: AnyObjectHandler()})
from matplotlib.legend_handler import HandlerPatch
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
class HandlerEllipse(HandlerPatch):
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
p = mpatches.Ellipse(xy=center, width=width + xdescent,
height=height + ydescent)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
c = mpatches.Circle((0.5, 0.5), 0.25, facecolor="green",
edgecolor="red", linewidth=3)
plt.gca().add_patch(c)
plt.legend([c], ["An ellipse, not a rectangle"],
handler_map={mpatches.Circle: HandlerEllipse()})
matplotlib中plt.legend使用方法
python中关于图例legend在图外的画法简析
python科学计算学习二:matplotlib绘图,图标注释(2)
python Matplotlib 系列教程(二)—— 图例,标题和标签的使用
显示图例(legend)
matplotlib的legend函数解释说明
Python可视化: 颜色 图例 实例(matplotlib饼状图)总结
Python数据可视化编程(三)
Python 3下Matplotlib画图中文显示乱码的解决方法
Matplotlib绘图汉字不能正常显示问题
没有更多推荐了,知乎 - 发现更大的世界有问题,上知乎。知乎作为中文互联网最大的知识分享平台,以「知识连接一切」为愿景,致力于构建一个人人都可以便捷接入的知识分享网络,让人们便捷地与世界分享知识、经验和见解,发现更大的世界。Inconspicuous手机验证码登录忘记密码?登录没有帐号?注册下载知乎 App自组织映射网络(SOM)介绍与Python实现 - 简书
自组织映射网络(SOM)介绍与Python实现
github源码:
自组织映射网络(Self-organizing Mapping)是一种常用的聚类方法。
som_structure.png
它常分为输入层与竞争层(输出层)。
输入层:假设一个输入样本为X=[x1,x2,x3,…,xn],是一个n维向量,则输入层神经元个数为n个。
竞争层:通常输出层的神经元以矩阵方式排列在二维空间中,每个神经元都有一个权值向量,权值向量维度与输入层样本维度相同。假设输出层有m个神经元,则有m个权值向量。
注意上图中的$x_i$为第i个样本
初始化:初始化竞争层m的数目与m个元素的权值向量
输入比较:样本输入网络,通过比较样本与m个权值向量的相似性,记相似性最大的竞争层节点为获胜者
调整权值:更新获胜者节点的权值
循环迭代:重复2,3
每个竞争层节点的权值可以初始化为(0, 1)之间的随机数。
import random
def initOutputLayer(m, n):
# m为竞争层节点数目;n为每一个节点的维度
layers = []
random.seed()
for i in range(m):
# 每一个节点
for j in range(n):
unit.append(round(random.random(),2))
layers.append(unit)
return layers
layers = initOutputLayer(m, n)
print("Output layers:", layers)
Output layers: [[0.33, 0.71], [0.34, 0.84], [0.58, 0.68], [0.78, 0.67], [0.03, 0.05]]
做比较之间可以先对所有的竞争层节点权值向量与输入向量归一化,然后再使用如欧式距离比较相似度。
竞争层第j个节点的权值归一化计算方式:$W_j=\dfrac{W_j}{||W_j||}$
输入向量归一化计算方式:$X=\dfrac{X}{||X||}$
两个维度都为n的向量之间的欧式距离计算方式:
som_udistance.png
这里$X$与$W_j$都是n维向量
||X||为二范数,其代表该向量的长度,是一个标量
相似度比较函数可参考:
import numpy.linalg as LA
# 计算范数
import math
def normalization(v):
norm = LA.norm(v, 2)
# 计算2范数
v_new = []
for i in range(len(v)):
v_new.append(round(v[i]/norm,2))
# 保留2位小数
return v_new
def normalizationVList(X):
X_new = []
for x in X:
X_new.append(normalization(x))
return X_new
def calSimilarity(x, y):
# 计算x,y两个向量的相似度
if len(x)!=len(y):
raise "维度不一致!"
for i in range(len(x)):
c += pow((x[i] - y[i]), 2)
math.sqrt(c)
def getWinner(x, layers):
# 找到layers里面与x最相似的节点
# x = normalization(x)
# layers = normalizationVList(layers)
min_value = 100000
# 存储最短距离
min_index = -1
# 存储跟x最相似节点的竞争层节点index
for i in range(len(layers)):
v = calSimilarity(x, layers[i])
if v & min_value:
min_value = v
min_index = i
return min_index
# 返回获胜节点index
# 输入数据处理
X = [[1, 2], [3, 4], [5, 6], [7, 8], [2, 3]]
# 输入列表
X_norm = normalizationVList(X)
print("Inputs normalization:", X_norm)
# 输入数据归一化
# 权值处理
layers_norm = normalizationVList(layers)
print("Weights normalization:", layers_norm)
# 权值归一化
# 计算某一个x输入的竞争层胜利节点
winner_index = getWinner(X_norm[0], layers_norm)
print("Winner index:", winner_index)
Inputs normalization: [[0.45, 0.89], [0.6, 0.8], [0.64, 0.77], [0.66, 0.75], [0.55, 0.83]]
Weights normalization: [[0.42, 0.91], [0.38, 0.93], [0.65, 0.76], [0.76, 0.65], [0.51, 0.86]]
Winner index: 0
竞争胜利的单元可以调整自己的权值,调整方式可以采用如下方式:
$w(t+1) = w(t) + \alpha(x-w(t))$
其中$\alpha$为学习率,它可以通过如下式子计算:
$\alpha=f(t)e^{-n}$ (其中f(t)为迭代次数的倒数)
def adjustWeight(w, x, alpha):
# w为要调整的权值向量;x为输入向量;alpha为学习率
if len(w)!=len(x):
raise "w,x维度应该相等!"
w_new = []
for i in range(len(w)):
w_new.append(w[i] + alpha*(x[i] - w[i]))
return w_new
alpha = 0.5
# 学习参数
print("After Adjust:", adjustWeight(layers[winner_index], X[0], alpha))
After Adjust: [0.665, 1.355]
重复输入比较与调整权值,可以选择在以下条件成立时结束迭代:
学习率小于某个阈值
达到预设的迭代次数
完整代码如下所示。
import random
import matplotlib.pyplot as plt
def createData(num, dim):
# 数据组数与数据维度
for i in range(num):
for j in range(dim):
pair.append(random.random())
data.append(pair)
return data
# 参数设置
train_times = 10
# 训练次数
data_dim = 2 # 数据维度
train_num = 160
test_num = 40
learn_rate = 0.5
# 学习参数
# 生成数据
random.seed()
# 生成训练数据
train_X = createData(train_num, data_dim)
# 生成测试数据
test_X = createData(test_num, data_dim)
# print(test_X)
# 初始化m个类
layers = initOutputLayer(m, data_dim)
print("Original layers:", layers)
# 开始迭代训练
while train_times & 0:
for i in range(train_num):
# 权值归一化
layers_norm = normalizationVList(layers)
# 计算某一个x输入的竞争层胜利节点
winner_index = getWinner(train_X[i], layers_norm)
# 修正权值
layers[winner_index] = adjustWeight(layers[winner_index], train_X[i], learn_rate)
train_times -= 1
print("After train layers:", layers)
for i in range(test_num):
# 权值归一化
layers_norm = normalizationVList(layers)
# 计算某一个x输入的竞争层胜利节点
winner_index = getWinner(test_X[i], layers_norm)
color = "ro"
if winner_index == 0:
color = "ro"
elif winner_index == 1:
color = "bo"
elif winner_index == 2:
color = "yo"
plt.plot(test_X[i][0], test_X[i][1], color)
plt.legend()
plt.show()
No handles with labels found to put in legend.
Original layers: [[0.02, 0.89], [0.89, 0.51], [0.04, 0.37]]
After train layers: [[0.61], [0.37], [0.36]]
output_10_2.png
我老婆现在是个标准的佛教徒,家里有蚊子她是不让打的。她的做法是,等蚊子降落在某面够得着的墙壁上,她手持一个透明的塑料碗蹑手蹑脚的走近,然后出其不意的扣住,左手压住碗,右手用一片薄纸板插入墙与碗的缝隙,左右手灵巧配合,蚊子就算被活捉了。然后她拿到阳台上打开窗户放生。 我根本没...
——龍·茶館 清平宋词好伴茶, 瑰丽唐诗入酒香; 吟诗侃侃更醉茶, 闻词不语比酒香。
第一次白日做梦: 孩子出生后,有了自己当老板的梦想。 在孩子10个月时,个人决定辞去工厂的正式工作,没有任何资金及美容基础知识下,一个人又是老板又是员工,开启了美容创业之路。第一次实现老板的梦。(初生牛犊不怕虎) 第二次白日做梦: 买上带电梯的高层楼房。 在没有任何资金下,...
晚上睡觉做了个相当开心的梦。 梦见朴宝剑在我身边,我们一起吃烧烤,我挎着他,和他拍照聊天。笑醒。
写下这个标题,我突然感觉到自己活的很累。了解我的人知道我是不快乐的,不了解我的人也会认为我有病。你说的没错,我有病,还是没药医的那种…… 人就是那样,越是想得到的越是不愿意说出来。比如名誉,金钱和美女。越是拥有的越是不想让别人知道,比如财富,权力和能力。 但是,你快不快乐你...python - Legend format lost after using: ax.legend(handles, labels ) - Stack Overflow
to customize your list.
This site uses cookies to deliver our services and to show you relevant ads and job listings.
By using our site, you acknowledge that you have read and understand our , , and our .
Your use of Stack Overflow’s Products and Services, including the Stack Overflow Network, is subject to these policies and terms.
Join Stack Overflow to learn, share knowledge, and build your career.
or sign in with
I have the same problem as in this post: Where the user wants to delete repeated entries in the legend:
The answer works for me as well, however, when I use it, the legend format is completely lost. This happens when I apply the ax.legend(handles, labels) method. The following code (copied from ) illustrates this issue:
# Example data
a = np.arange(0,3, .02)
b = np.arange(0,3, .02)
c = np.exp(a)
d = c[::-1]
# Create plots with pre-defined labels.
# Alternatively, you can pass labels explicitly when calling `legend`.
fig, ax = plt.subplots()
ax.plot(a, c, 'k--', label='Model length')
ax.plot(a, d, 'k:', label='Data length')
ax.plot(a, c+d, 'k', label='Total message length')
# Now add the legend with some customizations.
legend = ax.legend(loc='upper center', shadow=True)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels )
# The frame is matplotlib.patches.Rectangle instance surrounding the legend.
frame = legend.get_frame()
frame.set_facecolor('0.90')
# Set the fontsize
for label in legend.get_texts():
label.set_fontsize('large')
for label in legend.get_lines():
label.set_linewidth(1.5)
# the legend line width
plt.show()
Result without using 'ax.legend(handles, labels)':
Resul using 'ax.legend(handles, labels)':
Any advice would be most welcomed
EDIT 1: Typo 'without' corrected
You have issued legend() call twice and the second time it is called without formatting arguments, replace:
legend = ax.legend(loc='upper center', shadow=True)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels )
handles, labels = ax.get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
ax.legend(by_label.values(), by_label.keys(), loc='upper center', shadow=True)
Should do the trick.
29.5k45981
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Post as a guest
Post as a guest
Post Your Answer
By clicking &Post Your Answer&, you acknowledge that you have read our updated ,
and , and that your continued use of the website is subject to these policies.
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled

我要回帖

更多关于 dancelegend 的文章

 

随机推荐