使用plt.plot在matplotlib中绘制多个折线图

我正在使用以下代码。

%matplotlib notebook
plt.style.use('seaborn-bright')

fig,ax = plt.subplots(figsize=(8,6), facecolor='w', edgecolor='blue')
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)

plt.title('Clubs of Severn Valley Petanque League - performance in years 2014-2019',color='purple',size=14.5,y=1.09)

ax.set_ylabel('Year', color='indigo',size=10)
ax.set_ylabel('Points won', color='darkblue',  fontdict={'fontsize': 12, 'fontweight': 'medium'})

years=[2014,2015, 2016,2017,2018, 2019]
plt.xticks(np.arange(5), (years))
plt.margins(x=0.006,y=0.009)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()

ax.yaxis.set_major_formatter(plt.FuncFormatter('{:.0f}'.format))
ax.grid(True, 'major', 'y', ls='--', lw=.6, c='darkgray', alpha=.5)

ax.tick_params(axis='y', which='both', labelsize=10,bottom=False, top=False, labelbottom=True,
               left=False, right=False, labelleft=True)
plt.legend(loc=2)

# Now I call each column( one for each team) one by one like so :

plt.plot(final.Points_Kinver.values, marker='o', label='Kinver Con Club')
plt.plot(final.Points_Nomads.values, marker='o', label='Nomads')
plt.plot(final.Points_TopPub.values, marker='o', label='Top Pub')
plt.plot(final.Points_Plough.values, marker='o', label='Plough')
plt.plot(final.Points_AlveleyRoyals.values,  '-o', c='violet', label='Alveley Royals')
plt.plot(final.Points_Footloose.values, marker='o', c='yellow', label='Footloose')
plt.plot(final.Points_Gaters.values,  '-o', c='orange', label="Gaters 'A'")
plt.plot(final.Points_AlveleyOaks.values,  '-o',c='darkgreen',  label='Alveley Oaks') 


plt.show()

It works. Here is my chart enter image description here.

但是,我希望我可以将plt.plot写成一行,但是这不起作用,给了我一个空白的图表。

plt.plot(final.columns.values, marker='o')

这会导致错误。

TypeError                                 Traceback (most recent call last)
<ipython-input-277-f48c020019fc> in <module>()
     44 #mychart=final.plot( marker='o',ax=ax)
     45 
---> 46 plt.plot(final.columns.values, marker='o')
     47 
     48 #plt.plot(final.Points_Kinver.values, marker='o', label='Kinver Con Club')

~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in plot(*args, **kwargs)
   3356                       mplDeprecation)
   3357     try:
-> 3358         ret = ax.plot(*args, **kwargs)
   3359     finally:
   3360         ax._hold = washold

~\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
   1853                         "the Matplotlib list!)" % (label_namer, func.__name__),
   1854                         RuntimeWarning, stacklevel=2)
-> 1855             return func(ax, *args, **kwargs)
   1856 
   1857         inner.__doc__ = _add_data_doc(inner.__doc__,

~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, *args, **kwargs)
   1525         kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
   1526 
-> 1527         for line in self._get_lines(*args, **kwargs):
   1528             self.add_line(line)
   1529             lines.append(line)

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _grab_next_args(self, *args, **kwargs)
    404                 this += args[0],
    405                 args = args[1:]
--> 406             for seg in self._plot_args(this, kwargs):
    407                 yield seg
    408 

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
    381             x, y = index_of(tup[-1])
    382 
--> 383         x, y = self._xy_from_xy(x, y)
    384 
    385         if self.command == 'plot':

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _xy_from_xy(self, x, y)
    214         if self.axes.xaxis is not None and self.axes.yaxis is not None:
    215             bx = self.axes.xaxis.update_units(x)
--> 216             by = self.axes.yaxis.update_units(y)
    217 
    218             if self.command != 'plot':

~\Anaconda3\lib\site-packages\matplotlib\axis.py in update_units(self, data)
   1467         neednew = self.converter != converter
   1468         self.converter = converter
-> 1469         default = self.converter.default_units(data, self)
   1470         if default is not None and self.units is None:
   1471             self.set_units(default)

~\Anaconda3\lib\site-packages\matplotlib\category.py in default_units(data, axis)
    113         # default_units->axis_info->convert
    114         if axis.units is None:
--> 115             axis.set_units(UnitData(data))
    116         else:
    117             axis.units.update(data)

~\Anaconda3\lib\site-packages\matplotlib\category.py in __init__(self, data)
    180         self._counter = itertools.count(start=0)
    181         if data is not None:
--> 182             self.update(data)
    183 
    184     def update(self, data):

~\Anaconda3\lib\site-packages\matplotlib\category.py in update(self, data)
    199         for val in OrderedDict.fromkeys(data):
    200             if not isinstance(val, VALID_TYPES):
--> 201                 raise TypeError("{val!r} is not a string".format(val=val))
    202             if val not in self._mapping:
    203                 self._mapping[val] = next(self._counter)

TypeError: ('Points_Kinver',) is not a string

我也尝试过

final.plot( marker='o',ax=ax)

有用。但是,它删除了一些我精心编码的格式,更具体地说是刻度和网格线(ax.grid ...)。

您能解释一下为什么会在这里发生吗?

最好的方法是什么。我的下一步将是标记每行的末尾而不是图例,并且我所看到的代码包括df.columns。 所以我认为单行写会更好。

如您所见,我对matplotlib / python不太了解。我正在尝试通过为当地的地掷球协会创建可视化来进行练习。谢谢您对我的小项目的帮助。

评论