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

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

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

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

2233閲覧

python matplotlib 二つのグラフを一つにする方法(異なるY軸)

yaryo

総合スコア2

Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/03/21 11:08

わからないこと

以下のコードではどこでY軸をどのように分けて一緒のグラフにしているか教えていただきたいです。

python

1import matplotlib.pyplot as plt 2import matplotlib.cm as cm 3import numpy as np 4%matplotlib inline 5 6fig = plt.figure() 7ax1 = fig.add_subplot(111) 8t = np.linspace(0.0,10.0,1000) 9fs = 1.0 10y1 = np.sin(2.0*np.pi*fs*t) 11ln1=ax1.plot(t, y1,'C0',label=r'$y=sin(2\pi fst)$') 12 13ax2 = ax1.twinx() 14y2 = 10.0*t + 5.0 15ln2=ax2.plot(t,y2,'C1',label=r'$y=at+b$') 16 17h1, l1 = ax1.get_legend_handles_labels() 18h2, l2 = ax2.get_legend_handles_labels() 19ax1.legend(h1+h2, l1+l2, loc='lower right') 20 21ax1.set_xlabel('t') 22ax1.set_ylabel(r'$y=sin(2\pi fst)$') 23ax1.grid(True) 24ax2.set_ylabel(r'$y=at+b$')

目的は株価などの照らし合わせがしたく一つ一つのグラフは表示できるのですが、一緒のグラフにする方法を教えていただきたいです。
現状では一緒のグラフにはなっているのですが、Y軸のあたいが一緒のため過去データあの方が水平線になってしまいます。

python

1import pandas as pd 2import datetime 3from pandas_datareader import data 4import pandas as pd 5import matplotlib.pyplot as plt 6%matplotlib inline 7 8df = pd.read_csv('過去データあ.csv') 9df1 = pd.read_csv('過去データい.csv') 10 11 12df["日付け"] = df["日付け"].apply(lambda x: datetime.datetime.strptime(x, "%Y年%m月%d日")) 13df1["日付け"] = df1["日付け"].apply(lambda x: datetime.datetime.strptime(x, "%Y年%m月%d日")) 14 15df.sort_values(by="日付け", inplace=True) 16df1.sort_values(by="日付け", inplace=True) 17 18plt.figure(figsize=(30,10)) 19 20plt.plot(df['終値'], label='あ', color = 'g') 21plt.plot(df1['終値'], label='い')

よろしくお願い致します。

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

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

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

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

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

guest

回答1

0

ベストアンサー

ax2 = ax1.twinx()

が同じx軸を使うグラフを作っています。

python

1>>> print(ax1.twinx.__doc__) 2 3 Create a twin Axes sharing the xaxis. 4 5 Create a new Axes with an invisible x-axis and an independent 6 y-axis positioned opposite to the original one (i.e. at right). The 7 x-axis autoscale setting will be inherited from the original 8 Axes. To ensure that the tick marks of both y-axes align, see 9 `~matplotlib.ticker.LinearLocator`. 10![グラフ](d5d69dc0dbafa075e6733010c6925720.png) 11 Returns 12 ------- 13 ax_twin : Axes 14 The newly created Axes instance 15 16 Notes 17 ----- 18 For those who are 'picking' artists while using twinx, pick 19 events are only called for the artists in the top-most axes.

ラベルとか手抜きなので追加して下さい。

仮データ作成

python

1import pandas as pd 2import io 3 4indata1 = '''日付け 終値 52020-03-02 1015 62020-03-03 1025 72020-03-04 1050 82020-03-05 999 92020-03-06 1080''' 10 11with io.StringIO(indata1) as f: 12 df1 = pd.read_csv(f, sep=' +', engine='python', parse_dates=[0]) 13 14indata2 = '''日付け 終値 152020-03-02 3056 162020-03-03 3523 172020-03-04 4024 182020-03-05 5095 192020-03-06 3800''' 20 21with io.StringIO(indata2) as f: 22 df2 = pd.read_csv(f, sep=' +', engine='python', parse_dates=[0])

表示コード

python

1import pandas as pd 2import datetime 3import matplotlib.pyplot as plt 4import matplotlib.dates as mdates 5import numpy as np 6 7Date = df1["日付け"].values.astype(np.datetime64) 8EP1 = df1['終値'].values 9EP2 = df2['終値'].values 10 11fig = plt.figure(figsize=(30,10)) 12ax = fig.add_subplot(111) 13ax.plot(Date, EP1,'C0') 14ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d')) 15ax2 = ax.twinx() 16ax2.plot(Date, EP2,'C1') 17ax2.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d')) 18plt.show()

実行結果

イメージ説明

投稿2021/03/21 12:05

編集2021/03/21 14:09
ppaul

総合スコア24666

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

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

yaryo

2021/03/21 12:25

回答ありがとうございます。 ax2 = ax1.twinx()これを質問の下のpythonコードで使うにはどうしましょう? 日付をX軸にしたくて中身は2020-03-06こんな感じになっています。 形とかを変えなければいけないでしょうか? よろしくお願い致します。
ppaul

2021/03/21 14:10

回答に追加しました。 図の右上の赤丸は別のソフトが出しているものですので無視してください。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問