質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
pandas

Pandasは、PythonでRにおけるデータフレームに似た型を持たせることができるライブラリです。 行列計算の負担が大幅に軽減されるため、Rで行っていた集計作業をPythonでも比較的簡単に行えます。 データ構造を変更したりデータ分析したりするときにも便利です。

Q&A

2回答

3441閲覧

Pandasのdf.plotで日付をフォーマットで表示したい

barobaro

総合スコア1286

pandas

Pandasは、PythonでRにおけるデータフレームに似た型を持たせることができるライブラリです。 行列計算の負担が大幅に軽減されるため、Rで行っていた集計作業をPythonでも比較的簡単に行えます。 データ構造を変更したりデータ分析したりするときにも便利です。

0グッド

1クリップ

投稿2018/08/11 03:42

df.plot.bar()で日付を'%m/%d'で表示したいのですがエラーがでます。

python

1import io 2 3import pandas as pd 4import matplotlib.pyplot as plt 5import matplotlib.dates as mdates 6 7data = """ 82018-08-01,10,100 92018-08-02,20,200 102018-08-03,30,300 112018-08-04,40,400 122018-08-05,50,500 132018-08-06,60,600 142018-08-07,70,700 15""" 16df = pd.read_csv(io.StringIO(data), header=None, index_col=0) 17df.index = pd.to_datetime(df.index)

python

1ax = df.plot.bar() 2ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))

shell

1ValueError: 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()

df.plot()やdf.plot.bar()だと表示されるのですが

python

1df.plot()

イメージ説明

python

1df.plot.bar()

イメージ説明

python

1ax = df.plot() 2ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d')) 3# 日にちが一日ずれる 8/1=>7/31、8/7=>8/6

イメージ説明

python

1ax = df.plot.bar() 2ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))

sheel

1--------------------------------------------------------------------------- 2ValueError Traceback (most recent call last) 3/usr/local/lib/python3.6/dist-packages/IPython/core/formatters.py in __call__(self, obj) 4 332 pass 5 333 else: 6--> 334 return printer(obj) 7 335 # Finally look for special method names 8 336 method = get_real_method(obj, self.print_method) 9 10/usr/local/lib/python3.6/dist-packages/IPython/core/pylabtools.py in <lambda>(fig) 11 239 12 240 if 'png' in formats: 13--> 241 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs)) 14 242 if 'retina' in formats or 'png2x' in formats: 15 243 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs)) 16 17/usr/local/lib/python3.6/dist-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs) 18 123 19 124 bytes_io = BytesIO() 20--> 125 fig.canvas.print_figure(bytes_io, **kw) 21 126 data = bytes_io.getvalue() 22 127 if fmt == 'svg': 23 24/usr/local/lib/python3.6/dist-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs) 25 2214 orientation=orientation, 26 2215 dryrun=True, 27-> 2216 **kwargs) 28 2217 renderer = self.figure._cachedRenderer 29 2218 bbox_inches = self.figure.get_tightbbox(renderer) 30 31/usr/local/lib/python3.6/dist-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs) 32 505 33 506 def print_png(self, filename_or_obj, *args, **kwargs): 34--> 507 FigureCanvasAgg.draw(self) 35 508 renderer = self.get_renderer() 36 509 original_dpi = renderer.dpi 37 38/usr/local/lib/python3.6/dist-packages/matplotlib/backends/backend_agg.py in draw(self) 39 428 # if toolbar: 40 429 # toolbar.set_cursor(cursors.WAIT) 41--> 430 self.figure.draw(self.renderer) 42 431 finally: 43 432 # if toolbar: 44 45/usr/local/lib/python3.6/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 46 53 renderer.start_filter() 47 54 48---> 55 return draw(artist, renderer, *args, **kwargs) 49 56 finally: 50 57 if artist.get_agg_filter() is not None: 51 52/usr/local/lib/python3.6/dist-packages/matplotlib/figure.py in draw(self, renderer) 53 1297 54 1298 mimage._draw_list_compositing_images( 55-> 1299 renderer, self, artists, self.suppressComposite) 56 1300 57 1301 renderer.close_group('figure') 58 59/usr/local/lib/python3.6/dist-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite) 60 136 if not_composite or not has_images: 61 137 for a in artists: 62--> 138 a.draw(renderer) 63 139 else: 64 140 # Composite any adjacent images together 65 66/usr/local/lib/python3.6/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 67 53 renderer.start_filter() 68 54 69---> 55 return draw(artist, renderer, *args, **kwargs) 70 56 finally: 71 57 if artist.get_agg_filter() is not None: 72 73/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe) 74 2435 renderer.stop_rasterizing() 75 2436 76-> 2437 mimage._draw_list_compositing_images(renderer, self, artists) 77 2438 78 2439 renderer.close_group('axes') 79 80/usr/local/lib/python3.6/dist-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite) 81 136 if not_composite or not has_images: 82 137 for a in artists: 83--> 138 a.draw(renderer) 84 139 else: 85 140 # Composite any adjacent images together 86 87/usr/local/lib/python3.6/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 88 53 renderer.start_filter() 89 54 90---> 55 return draw(artist, renderer, *args, **kwargs) 91 56 finally: 92 57 if artist.get_agg_filter() is not None: 93 94/usr/local/lib/python3.6/dist-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs) 95 1131 renderer.open_group(__name__) 96 1132 97-> 1133 ticks_to_draw = self._update_ticks(renderer) 98 1134 ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw, 99 1135 renderer) 100 101/usr/local/lib/python3.6/dist-packages/matplotlib/axis.py in _update_ticks(self, renderer) 102 972 103 973 interval = self.get_view_interval() 104--> 974 tick_tups = list(self.iter_ticks()) 105 975 if self._smart_bounds and tick_tups: 106 976 # handle inverted limits 107 108/usr/local/lib/python3.6/dist-packages/matplotlib/axis.py in iter_ticks(self) 109 919 self.major.formatter.set_locs(majorLocs) 110 920 majorLabels = [self.major.formatter(val, i) 111--> 921 for i, val in enumerate(majorLocs)] 112 922 113 923 minorLocs = self.minor.locator() 114 115/usr/local/lib/python3.6/dist-packages/matplotlib/axis.py in <listcomp>(.0) 116 919 self.major.formatter.set_locs(majorLocs) 117 920 majorLabels = [self.major.formatter(val, i) 118--> 921 for i, val in enumerate(majorLocs)] 119 922 120 923 minorLocs = self.minor.locator() 121 122/usr/local/lib/python3.6/dist-packages/matplotlib/dates.py in __call__(self, x, pos) 123 572 def __call__(self, x, pos=0): 124 573 if x == 0: 125--> 574 raise ValueError('DateFormatter found a value of x=0, which is ' 126 575 'an illegal date. This usually occurs because ' 127 576 'you have not informed the axis that it is ' 128 129ValueError: 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()

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

https://teratail.com/questions/156739

を参考にしたら折れ線と棒グラフ(ひとつ)ならできました

python

1plt.plot(df) 2 3# X軸のフォーマットを設定 4plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%m/%d")) 5 6plt.show()

イメージ説明

python

1plt.bar(df.index, df[1]) 2 3# X軸のフォーマットを設定 4plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%m/%d")) 5 6plt.show()

イメージ説明

投稿2018/11/07 15:03

barobaro

総合スコア1286

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

文字にすると表示できました

python

1df1 = df.copy() 2df1.index = df.index.strftime("%m/%d") 3df1.plot.bar(rot=0)

イメージ説明

python

1fig, ax = plt.subplots() 2ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d')) 3 4ax.bar(df.index, df[2], width=0.2, label='2', align='center') 5ax.bar(df.index, df[1], width=0.2, label='1', align='center') 6 7ax.legend(loc="best")

イメージ説明

あとはバーをずらせれたら完成なんだけど

投稿2018/10/27 11:32

編集2018/10/27 13:27
barobaro

総合スコア1286

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問