如何使用pyplot和dict作为关键字参数的输入

2024-04-20 05:11:52 发布

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

我想使用dicts作为pyplot中不同绘图类型的keyword参数的输入。我的目的是从下面的代码中获取plt.bar(x,y,bottom=10)

import matplotlib

matplotlib.use('Agg')

import matplotlib.pyplot as plt


x=[15,20,30,40,50]

y=[1.2,1.7,3,4.5,1.4]

dd={'bottom': 10}

plt.bar(x,y,*dd)

plt.savefig("test.png")
Traceback (most recent call last):
  File "/home/xx/.local/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 2127, in _convert_dx
    dx = [convert(x0 + ddx) - x for ddx in dx]
  File "/home/xx/.local/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 2127, in <listcomp>
    dx = [convert(x0 + ddx) - x for ddx in dx]
TypeError: unsupported operand type(s) for +: 'int' and 'str'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/xx/.local/lib/python3.8/site-packages/matplotlib/axis.py", line 1500, in convert_units
    ret = self.converter.convert(x, self.units, self)
  File "/home/xx/.local/lib/python3.8/site-packages/matplotlib/category.py", line 49, in convert
    raise ValueError(
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:

Traceback (most recent call last):
  File "pythontest.py", line 10, in <module>
    plt.bar(x,y,*dd)
  File "/home/xx/.local/lib/python3.8/site-packages/matplotlib/pyplot.py", line 2651, in bar
    return gca().bar(
  File "/home/xx/.local/lib/python3.8/site-packages/matplotlib/__init__.py", line 1361, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "/home/xx/.local/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 2294, in bar
    width = self._convert_dx(width, x0, x, self.convert_xunits)
  File "/home/xx/.local/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 2133, in _convert_dx
    dx = convert(dx)
  File "/home/xx/.local/lib/python3.8/site-packages/matplotlib/artist.py", line 203, in convert_xunits
    return ax.xaxis.convert_units(x)
  File "/home/xx/.local/lib/python3.8/site-packages/matplotlib/axis.py", line 1502, in convert_units
    raise munits.ConversionError('Failed to convert value(s) to axis '
matplotlib.units.ConversionError: Failed to convert value(s) to axis units: 'bottom'

Tags: inpyconverthomematplotliblibpackageslocal