简体   繁体   English

具有不同 y 轴的同一可视化中的 2 个线图

[英]2 line-plots in same visualization with different y-axis

I am quite stuck with this one.我很坚持这个。 I am trying to create a line diagram with the same x-axis scale (years) but a different y-axis scale How can I do that?我正在尝试创建一个具有相同 x 轴刻度(年)但不同 y 轴刻度的折线图我该怎么做?

I have two datasets with this info:我有两个包含此信息的数据集:

test_data1.head()
   latitude longitude   place       year
0   36.087  -106.168    New Mexico  1973
1   33.917  -90.775     Mississippi 1973
2   37.160  -104.594    Colorado    1973
3   37.148  -104.571    Colorado    1973
4   36.500  -100.693    Oklahoma    1974

test_data2.head()
    LAT          LONG       BBLS    Year
0   36.900324   -98.21826   300     1977.0
1   36.896636   -98.17772   1,000   2002.0
2   36.806113   -98.32584   1,000   1988.0
3   36.888589   -98.31853   1,000   1985.0
4   36.892128   -98.19462   2,400   2002.0

for context, test_data1 refers to earthquakes and test_data2 refers to injection wells and BBLS is the number of barrels produced.对于上下文,test_data1 是指地震,test_data2 是指注入井,BBLS 是生产的桶数。

What I want to do is create a line diagram showing the number of earthquakes per year, and the number of barrels produced per year from 1980. I want to display the number of earthquakes per year on the left (y1) and the number of barrels produced per year on the right (y2).我想做的是创建一个线图,显示每年的地震次数,以及从 1980 年以来每年生产的桶数。我想在左侧显示每年的地震次数(y1)和桶数右边的年产量 (y2)。

Here's what I've done but it didn't work, anyone knows why or show me a way to do it?这是我所做的,但它没有用,有人知道为什么或告诉我一种方法吗?

import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
%matplotlib  inline 

x=test_data1['year']
y1 = test_data1['place']
y2 = test_data2['BBLS']

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
curve1 = ax1.plot (x, y1, label='Number of Earthquakes', color='r')
curve2= ax2.plot (x, y2, label='Number of Barrels Produced', color='b')
plt.plot()
plt.show()

I'm getting this huge error but I can't understand it since I am new to Python:我收到了这个巨大的错误,但我无法理解它,因为我是 Python 的新手:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-109-9e26d5f7e5e2> in <module>
     11 ax2 = ax1.twinx()
     12 curve1 = ax1.plot (x, y1, label='Number of Earthquakes', color='r')
---> 13 curve2= ax2.plot (x, y2, label='Number of Barrels Produced', color='b')
     14 plt.plot()
     15 plt.show()

~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1741         """
   1742         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1743         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1744         for line in lines:
   1745             self.add_line(line)

~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in __call__(self, data, *args, **kwargs)
    271                 this += args[0],
    272                 args = args[1:]
--> 273             yield from self._plot_args(this, kwargs)
    274 
    275     def get_next_color(self):

~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
    394             self.axes.xaxis.update_units(x)
    395         if self.axes.yaxis is not None:
--> 396             self.axes.yaxis.update_units(y)
    397 
    398         if x.shape[0] != y.shape[0]:

~\anaconda3\lib\site-packages\matplotlib\axis.py in update_units(self, data)
   1461         neednew = self.converter != converter
   1462         self.converter = converter
-> 1463         default = self.converter.default_units(data, self)
   1464         if default is not None and self.units is None:
   1465             self.set_units(default)

~\anaconda3\lib\site-packages\matplotlib\category.py in default_units(data, axis)
    105         # the conversion call stack is default_units -> axis_info -> convert
    106         if axis.units is None:
--> 107             axis.set_units(UnitData(data))
    108         else:
    109             axis.units.update(data)

~\anaconda3\lib\site-packages\matplotlib\category.py in __init__(self, data)
    174         self._counter = itertools.count()
    175         if data is not None:
--> 176             self.update(data)
    177 
    178     @staticmethod

~\anaconda3\lib\site-packages\matplotlib\category.py in update(self, data)
    209         for val in OrderedDict.fromkeys(data):
    210             # OrderedDict just iterates over unique values in data.
--> 211             cbook._check_isinstance((str, bytes), value=val)
    212             if convertible:
    213                 # this will only be called so long as convertible is True.

~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py in _check_isinstance(_types, **kwargs)
   2244     for k, v in kwargs.items():
   2245         if not isinstance(v, types):
-> 2246             raise TypeError(
   2247                 "{!r} must be an instance of {}, not a {}".format(
   2248                     k,

TypeError: 'value' must be an instance of str or bytes, not a float

Still, Jupiter produces some plot which ofc isn't what I am looking for, not to mention that I am obtaining the y1 in terms of place but I do want just to count the number of earthquakes in a year, I just felt that using the 'place' would make the code just to count.尽管如此,木星还是产生了一些 plot 这不是我想要的,更不用说我在地点方面获得了 y1 但我只想计算一年中的地震次数,我只是觉得使用“地方”将使代码只是为了计数。 Please, help.请帮忙。

在此处输入图像描述

Here are the datasets I am working on in case it's useful.以下是我正在处理的数据集,以防万一有用。 Note that they have many more columns but I am not using them as they aren't relevant for this graphic.请注意,它们还有更多列,但我没有使用它们,因为它们与此图形无关。

okQuakes.csv (test_data1) InjectionWells.csv (test_data2) okQuakes.csv (test_data1) InjectionWells.csv (test_data2)

Share axis before the creation with sharex Like this创建前用sharex共享轴 像这样

y2 = test_data2['BBLS'].astype(str)

fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)

curve1 = ax1.plot (x, y1, label='Number of Earthquakes', color='r')
curve2= ax2.plot (x, y2, label='Number of Barrels Produced', color='b')
plt.plot()
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM