Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向分组面积图中的x轴添加日期_Python_Matplotlib_Graph_Data Visualization - Fatal编程技术网

Python 向分组面积图中的x轴添加日期

Python 向分组面积图中的x轴添加日期,python,matplotlib,graph,data-visualization,Python,Matplotlib,Graph,Data Visualization,我正在尝试像这样绘制分组面积图,除了在x轴、y轴和标题上有标签 到目前为止,我已经做到了 但实际数据并没有像预期的那样出现在图表中 当我取消注释行area\u plot.set\u xlim(xmin=datemin,xmax=datemax)时,数据会显示出来,但x轴没有单位 我不知道这是否是因为我想要的x轴单位是“日期”,它当前将我的日期解释为直数,我需要在某个地方包含ax.xaxis_date()来转换单位,但当我取消注释area_plot.xaxis_date()时,我得到以下错误: T

我正在尝试像这样绘制分组面积图,除了在x轴、y轴和标题上有标签

到目前为止,我已经做到了 但实际数据并没有像预期的那样出现在图表中

当我取消注释行
area\u plot.set\u xlim(xmin=datemin,xmax=datemax)
时,数据会显示出来,但x轴没有单位

我不知道这是否是因为我想要的x轴单位是“日期”,它当前将我的日期解释为直数,我需要在某个地方包含
ax.xaxis_date()
来转换单位,但当我取消注释
area_plot.xaxis_date()
时,我得到以下错误:

There was a problem running this cell
ValueError DateFormatter found a value of x=0, which is an illegal date.  This usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date()
我还尝试取消注释
plt.xticks(np.arange(0,len(x1),12))
以使用索引而不是
login\u month
日期来创建适当的xticks,但它给出了错误:

Error in callback <function install_repl_displayhook.<locals>.post_execute at 0x7f5624809b70> (for post_execute):
There was a problem running this cell
ValueError DateFormatter found a value of x=0, which is an illegal date.  This usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date() ---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/pyplot.py in post_execute()
    147             def post_execute():
    148                 if matplotlib.is_interactive():
--> 149                     draw_all()
    150 
    151             # IPython >= 2

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/_pylab_helpers.py in draw_all(cls, force)
    134         for f_mgr in cls.get_all_fig_managers():
    135             if force or f_mgr.canvas.figure.stale:
--> 136                 f_mgr.canvas.draw_idle()
    137 
    138 atexit.register(Gcf.destroy_all)

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/backend_bases.py in draw_idle(self, *args, **kwargs)
   2053         if not self._is_idle_drawing:
   2054             with self._idle_draw_cntx():
-> 2055                 self.draw(*args, **kwargs)
   2056 
   2057     def draw_cursor(self, event):

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    435             # if toolbar:
    436             #     toolbar.set_cursor(cursors.WAIT)
--> 437             self.figure.draw(self.renderer)
    438             # A GUI class may be need to update a window using this draw, so
    439             # don't forget to call the superclass.

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/figure.py in draw(self, renderer)
   1491 
   1492             mimage._draw_list_compositing_images(
-> 1493                 renderer, self, artists, self.suppressComposite)
   1494 
   1495             renderer.close_group('figure')

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2633             renderer.stop_rasterizing()
   2634 
-> 2635         mimage._draw_list_compositing_images(renderer, self, artists)
   2636 
   2637         renderer.close_group('axes')

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    139     if not_composite or not has_images:
    140         for a in artists:
--> 141             a.draw(renderer)
    142     else:
    143         # Composite any adjacent images together

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1188         renderer.open_group(__name__)
   1189 
-> 1190         ticks_to_draw = self._update_ticks(renderer)
   1191         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1192                                                                 renderer)

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/axis.py in _update_ticks(self, renderer)
   1026 
   1027         interval = self.get_view_interval()
-> 1028         tick_tups = list(self.iter_ticks())  # iter_ticks calls the locator
   1029         if self._smart_bounds and tick_tups:
   1030             # handle inverted limits

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/axis.py in iter_ticks(self)
    973         self.major.formatter.set_locs(majorLocs)
    974         majorLabels = [self.major.formatter(val, i)
--> 975                        for i, val in enumerate(majorLocs)]
    976 
    977         minorLocs = self.minor.locator()

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/axis.py in <listcomp>(.0)
    973         self.major.formatter.set_locs(majorLocs)
    974         majorLabels = [self.major.formatter(val, i)
--> 975                        for i, val in enumerate(majorLocs)]
    976 
    977         minorLocs = self.minor.locator()

/opt/conda/envs/python3/lib/python3.6/site-packages/matplotlib/dates.py in __call__(self, x, pos)
    628     def __call__(self, x, pos=0):
    629         if x == 0:
--> 630             raise ValueError('DateFormatter found a value of x=0, which is '
    631                              'an illegal date.  This usually occurs because '
    632                              'you have not informed the axis that it is '
这是我到目前为止编写的实际代码

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

area_plot = (df.pivot(index='login_month',
          columns='user_month_created',
          values='cumulative_logins')
   .plot.area(figsize=(20,18))
)

#labels
plt.title('cumulative monthly logins by user creation cohort month')
plt.xlabel('login month')
plt.ylabel('cumulative monthly logins (in tens of millions)')

#ticks

# plt.xticks(x, 'bbbb')
years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
years_fmt = mdates.DateFormatter('%Y')

# format the ticks
area_plot.xaxis.set_major_locator(years)
area_plot.xaxis.set_major_formatter(years_fmt)
area_plot.xaxis.set_minor_locator(months)

# round to nearest years.
datemin = np.datetime64(df['login_month'][0], 'M')
datemax = np.datetime64(df['login_month'][1294], 'M') + np.timedelta64(1, 'Y')
area_plot.set_xlim(xmin=datemin, xmax=datemax)

x1=df['login_month']
# area_plot.xaxis_date()

# plt.xticks(np.arange(0, len(x1), 12))
plt.yticks(np.arange(0, 11000000, 250000))

plt.grid(True)
这是我得到的(显然)不完整的结果,完全忽略了数据:

编辑:

在顶部添加
df['login\u month']=pd.to\u datetime(df['login\u month'])
之后,我

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df['login_month'] = pd.to_datetime(df['login_month'])

area_plot = (df.pivot(index='login_month',
          columns='user_month_created',
          values='cumulative_logins')
   .plot.area(figsize=(20,18))
)

#labels
plt.title('cumulative monthly logins by user creation cohort month')
plt.xlabel('login month')
plt.ylabel('cumulative monthly logins (in tens of millions)')

#ticks
years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
years_fmt = mdates.DateFormatter('%Y')

# format the ticks
# x_dates = df['login_month'].dt.strftime('%m-%d').sort_values().unique()
area_plot.xaxis.set_major_locator(years)
# area_plot.xaxis.set_major_formatter(plt.FixedFormatter(x_dates))
area_plot.xaxis.set_major_formatter(years_fmt)
area_plot.xaxis.set_minor_locator(months)

# round to nearest years.
datemin = np.datetime64(df['login_month'][0], 'M')
datemax = np.datetime64(df['login_month'][1294], 'M') + np.timedelta64(1, 'Y')
area_plot.set_xlim(xmin=datemin, xmax=datemax)

# x1=df['login_month']
# area_plot.xaxis_date()

# plt.xticks(np.arange(10, len(x1), 12))
plt.yticks(np.arange(0, 11000000, 250000))
plt.grid(True)

和下图,但x轴仍然无法显示:

确保索引列为datetime:
df['index']=pd.to_datetime(df['index'])
,然后再旋转。@QuangHoang感谢您的建议。我添加了它,但是x轴仍然没有显示,但是
区域\u plot.set\u xlim(xmin=datemin,xmax=datemax)
按预期工作
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df['login_month'] = pd.to_datetime(df['login_month'])

area_plot = (df.pivot(index='login_month',
          columns='user_month_created',
          values='cumulative_logins')
   .plot.area(figsize=(20,18))
)

#labels
plt.title('cumulative monthly logins by user creation cohort month')
plt.xlabel('login month')
plt.ylabel('cumulative monthly logins (in tens of millions)')

#ticks
years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
years_fmt = mdates.DateFormatter('%Y')

# format the ticks
# x_dates = df['login_month'].dt.strftime('%m-%d').sort_values().unique()
area_plot.xaxis.set_major_locator(years)
# area_plot.xaxis.set_major_formatter(plt.FixedFormatter(x_dates))
area_plot.xaxis.set_major_formatter(years_fmt)
area_plot.xaxis.set_minor_locator(months)

# round to nearest years.
datemin = np.datetime64(df['login_month'][0], 'M')
datemax = np.datetime64(df['login_month'][1294], 'M') + np.timedelta64(1, 'Y')
area_plot.set_xlim(xmin=datemin, xmax=datemax)

# x1=df['login_month']
# area_plot.xaxis_date()

# plt.xticks(np.arange(10, len(x1), 12))
plt.yticks(np.arange(0, 11000000, 250000))
plt.grid(True)