我需要从子图形在插入轴上绘制条形图.以下是生成子图和插入轴的代码(简化版本):

labels = ['A', 'B', 'C', 'D', 'E']
MAES = [np.random.rand() for i in range(len(labels))]

X = np.arange(0,4,.01)
Y = np.sin(X)

fig, axs = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
axs[0].plot(X,Y)
axs[1].bar(labels,MAES)

ax_in = axs[0].inset_axes([0.8, 0.1, 0.15, 0.15])

它会生成以下输出:

enter image description here

但现在,我需要做的是将罐子插入插图中.要做到这一点,我在最后ax_in.bar(labels,MAES)处加了一句.我得到的输出与之前相同,并且还出现以下错误:

ValueError                                Traceback (most recent call last)
File /usr/local/lib/python3.8/dist-packages/matplotlib/axis.py:1506, in Axis.convert_units(self, x)
   1505 try:
-> 1506     ret = self.converter.convert(x, self.units, self)
   1507 except Exception as e:

File /usr/local/lib/python3.8/dist-packages/matplotlib/category.py:49, in StrCategoryConverter.convert(value, unit, axis)
     48 if unit is None:
---> 49     raise ValueError(
     50         'Missing category information for StrCategoryConverter; '
     51         'this might be caused by unintendedly mixing categorical and '
     52         'numeric data')
     53 StrCategoryConverter._validate_unit(unit)

ValueError: Missing category information for StrCategoryConverter; this might be caused by unintendedly mixing categorical and numeric data

The above exception was the direct cause of the following exception:

ConversionError                           Traceback (most recent call last)
Input In [120], in <cell line: 13>()
     10 axs[1].bar(labels,MAES)
     12 ax_in = axs[0].inset_axes([0.8, 0.1, 0.15, 0.15])
---> 13 ax_in.bar(labels,MAES)

File /usr/local/lib/python3.8/dist-packages/matplotlib/__init__.py:1412, in inner(ax, data, *args, **kwargs)
   1404 assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, (
   1405     "Matplotlib internal error: invalid replace_names ({!r}) for {!r}"
   1406     .format(replace_names, func.__name__))
   1407 assert label_namer is None or label_namer in arg_names, (
   1408     "Matplotlib internal error: invalid label_namer ({!r}) for {!r}"
   1409     .format(label_namer, func.__name__))
   1411 @functools.wraps(func)
-> 1412 def inner(ax, *args, data=None, **kwargs):
   1413     if data is None:
   1414         return func(ax, *map(sanitize_sequence, args), **kwargs)

File /usr/local/lib/python3.8/dist-packages/matplotlib/axes/_axes.py:2331, in bar(self, x, height, width, bottom, align, **kwargs)

File /usr/local/lib/python3.8/dist-packages/matplotlib/artist.py:252, in convert_xunits(self, x)
    250 ax = getattr(self, 'axes', None)
    251 if ax is None or ax.xaxis is None:
--> 252     return x
    253 return ax.xaxis.convert_units(x)

File /usr/local/lib/python3.8/dist-packages/matplotlib/axis.py:1508, in Axis.convert_units(self, x)
   1506     ret = self.converter.convert(x, self.units, self)
   1507 except Exception as e:
-> 1508     raise munits.ConversionError('Failed to convert value(s) to axis '
   1509                                  f'units: {x!r}') from e
   1510 return ret

ConversionError: Failed to convert value(s) to axis units: ['A', 'B', 'C', 'D', 'E']

为什么条形图方法在轴子图中工作,而不是在插入轴中工作?我如何才能解决这个错误?

推荐答案

对于x轴值为strings的列表,inset_axes似乎玩得不好.要弥补这一点,请手动将x轴值设置为包含int个值和range(len(labels))个值的列表,以便它可以使用inset_axes个值.然后,将内置tick_label设置为plt.bar,并将其设置为等于您的实际x轴值:

labels = ['A', 'B', 'C', 'D', 'E']
MAES = [np.random.rand() for i in range(len(labels))]

X = np.arange(0,4,.01)
Y = np.sin(X)

fig, axs = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
axs[0].plot(X,Y)
axs[1].bar(labels,MAES)

# To make your x axis values essentially [0,1,2,3,4] (or however long your label list is)
x_value = range(len(labels))  

ax_in = axs[0].inset_axes([0.8, 0.1, 0.15, 0.15])
ax_in.bar(x_value,MAES, tick_label = labels)
plt.show()

输出:

enter image description here

Python相关问答推荐

Pandas 修改原始excel

Plotly Dash函数来切换图形参数-pPython

Python在通过Inbox调用时给出不同的响应

Python中的锁定类和线程以实现dict移动

从管道将Python应用程序部署到Azure Web应用程序,不包括需求包

LAB中的增强数组

如何调整spaCy token 化器,以便在德国模型中将数字拆分为行末端的点

在内部列表上滚动窗口

如何在msgraph.GraphServiceClient上进行身份验证?

大小为M的第N位_计数(或人口计数)的公式

如何过滤包含2个指定子字符串的收件箱列名?

将pandas Dataframe转换为3D numpy矩阵

通过pandas向每个非空单元格添加子字符串

对所有子图应用相同的轴格式

try 将一行连接到Tensorflow中的矩阵

Pandas—在数据透视表中占总数的百分比

matplotlib + python foor loop

幂集,其中每个元素可以是正或负""""

在Admin中显示从ManyToMany通过模型的筛选结果

具有相同图例 colored颜色 和标签的堆叠子图