为什么我得到这个NullReferenceException?(Why am I getting this NullReferenceException?)
我正在研究一个涉及一些自制的(de-)序列化代码的项目,并且我遇到了一些列表反序列化的问题。 下面的代码在第二行抛出一个NullReferenceException,即使var
list
不为空,并且在将鼠标悬停在它上面时,它会高兴地报告Count = 0
。System.Collections.IList list = ((System.Collections.IList)obj); list.Add(val);
我的变量被实例化有点奇怪,所以也许这有什么关系呢? 这是涉及的代码。
System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
type
是什么System.Type.GetType("System.Collections.Generic.List`1[[Networking.Client, Networking, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
任何帮助将非常感激 :)
I'm working on a project that involves some home-made (de-)serialization code, and I have run into some issues with the deserializing of a List. The following code is throwing a NullReferenceException on the second line, even though the var
list
is not null, and happily reportsCount = 0
when hovering my mouse over it.System.Collections.IList list = ((System.Collections.IList)obj); list.Add(val);
My variables are being instantiated a bit weird, so maybe that has got something to do with it? This is the code involved.
System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
Where
type
isSystem.Type.GetType("System.Collections.Generic.List`1[[Networking.Client, Networking, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Any help would be much appreciated :)
原文:https://stackoverflow.com/questions/583859
最满意答案
通过指定
label
参数来创建条形图的图例条目,与许多其他艺术家类似。ax.bar(...., label="my label") ax.legend()
完整的例子:
import matplotlib.pyplot as plt fig, ax = plt.subplots() train_errors = [1,2,3,4,5] val_errors = [2,1,4,2,3] test_errors = [5,4,3,2,1] X = list("ABCDE") x1 = [i-0.2 for i in range(len(train_errors))] x2 = [i for i in range(len(train_errors))] x3 = [i+0.2 for i in range(len(train_errors))] ax.bar(x1, train_errors, width=0.2, color='b', label="Train Errors") ax.bar(x2, val_errors, width=0.2, color='g', label="Val Errors") ax.bar(x3, test_errors, width=0.2, color='r', label="Test Errors") ax.set_xticks(x2) ax.set_xticklabels(X) ax.legend() ax.set_xlabel('Models') ax.set_ylabel('RMSE') ax.set_title('Regression Models Comparison') plt.show()
A legend entry for a bar plot, similar to many other artists, is created by specifiying the
label
argument.ax.bar(...., label="my label") ax.legend()
This is also shown in the first example in the documentation.
Complete example:
import matplotlib.pyplot as plt fig, ax = plt.subplots() train_errors = [1,2,3,4,5] val_errors = [2,1,4,2,3] test_errors = [5,4,3,2,1] X = list("ABCDE") x1 = [i-0.2 for i in range(len(train_errors))] x2 = [i for i in range(len(train_errors))] x3 = [i+0.2 for i in range(len(train_errors))] ax.bar(x1, train_errors, width=0.2, color='b', label="Train Errors") ax.bar(x2, val_errors, width=0.2, color='g', label="Val Errors") ax.bar(x3, test_errors, width=0.2, color='r', label="Test Errors") ax.set_xticks(x2) ax.set_xticklabels(X) ax.legend() ax.set_xlabel('Models') ax.set_ylabel('RMSE') ax.set_title('Regression Models Comparison') plt.show()
相关问答
更多-
您需要自己创建图例。 为此,创建一些未在图中显示的矩形(所谓的代理艺术家)。 #create legend handles = [Rectangle((0,0),1,1,color=c,ec="k") for c in [low,medium, high]] labels= ["low","medium", "high"] plt.legend(handles, labels) 完整的例子: import matplotlib.pyplot as plt import numpy as np from m ...
-
Matplotlib:如何在两个独立的轴上显示条形图和线条的图例?(Matplotlib: how to show legend for bar chart and line on 2 separate axes?)[2022-11-27]
关于python错误的好处是,它们通常可以从字面上理解并直接告诉你这个问题。 “TypeError”告诉你,你有一个类型的问题。 您可以打印类型: print(type(l1)) #print(type(l2)) # 现在,“只能将元组(不是”列表“)连接到元组”将告诉你不能将barcontainer添加到列表中。 简单解决方案:添加两个列表: myl=[l1]+l2 The good ... -
Python的matplotlib图例与gridspec分开的轴(Python's matplotlib legend in separate axis with gridspec)[2022-05-08]
您可以使用ax1.get_legend_handles_labels()从第一ax1.get_legend_handles_labels()图中获取图例句柄和标签,然后在第二个子图上创建图例时使用它们。 从文档 : get_legend_handles_labels(legend_handler_map=None) 返回图例的句柄和标签 ax.legend()相当于: h, l = ax.get_legend_handles_labels() ax.legend(h, l) import numpy a ... -
plt.legend()将隐含地调用ax的legend方法。 使用pyplot接口,你有时不清楚你正在处理哪个轴。 所以Matplotlib官方文档还建议使用ax方法 (面向对象的API)。 它给你更多的控制和定制。 plt.legend() will implicitly invoke the legend method of ax. Using the pyplot interface, you sometimes do not know explicitly which axes you are de ...
-
通过指定label参数来创建条形图的图例条目,与许多其他艺术家类似。 ax.bar(...., label="my label") ax.legend() 这也在文档的第一个例子中显示 。 完整的例子: import matplotlib.pyplot as plt fig, ax = plt.subplots() train_errors = [1,2,3,4,5] val_errors = [2,1,4,2,3] test_errors = [5,4,3,2,1] X = list("ABCDE" ...
-
在matplotlib中处理传说?(handle legend in matplotlib?)[2023-10-04]
该问题的代码绘制了3条线图。 但是,由于一条线需要两个点才能存在,并且只提供一个点( x=[0], y=[0] ),所以不会在画布上显示。 你有两个选择: 提供更多分数, ax.plot([0,2,3],[0,11,5]) 将该点的点显示为点, ax.plot([0],[0], marker="o") 命令plt.legend(loc="best")在图中放置一个图例。 如果你忽略它,就没有传说。 The code from the question draws 3 line plots. However, ... -
多行matplotlib文本的对齐方式由关键字参数multialignment (有关示例http://matplotlib.org/examples/pylab_examples/multiline.html,请参阅此处)。 因此,您可以将图例的标题文本居中,如下所示: l = plt.legend(['Lag ' + str(lag) for lag in all_x], loc='lower right', title='hello hello hello \n worl ...
-
你需要替换plt.draw() plt.gcf().canvas.draw() 或者,如果你有一个数字句柄, fig.canvas.draw() 。 这是必需的,因为图例位置仅在绘制画布时确定,之前它只是位于相同的位置。 使用plt.draw()是不够的,因为绘制图例需要使用后端的有效渲染器。 You would need to replace plt.draw() by plt.gcf().canvas.draw() or, if you have a figure handle, fig.canva ...
-
对于使用TextArea的解决方案,请参阅此答案 。 然后,您需要为TextArea的文本重新创建fontproperties。 因为在这里你想要在图例中准确显示你作为文本的符号,为一些文本对象创建图例处理程序的更简单的方法是将文本映射到TextHandler 。 TextHandler子类matplotlib.legend_handler.HandlerBase及其create_artists生成要在图例中显示的文本的副本。 然后需要为图例调整一些文本属性。 import matplotlib.pyplo ...
-
避免尝试在轴外排列盒子的噩梦的一种解决方案是使用带有textcolor乳胶标签。 以下代码 import matplotlib matplotlib.use('ps') from matplotlib import rc rc('text',usetex=True) rc('text.latex', preamble=r'\usepackage{color}') import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot( ...