PythonとMatplotlibを使ったグラフ描画練習問題10選:初心者から中級者までステップアップ!
Pythonは汎用性の高いプログラミング言語であり、データ分析や機械学習の分野で広く利用されています。その中でも、データの可視化にはMatplotlibが欠かせないライブラリです。本記事では、Matplotlibを使ったグラフ描画練習問題10選を、初心者から中級者までレベルに合わせて紹介します。各問題には解説とサンプルコードを記載し、読者の皆様のMatplotlibスキル向上に貢献することを目指します。
1. Matplotlibとは?なぜ学ぶ必要があるのか?
MatplotlibはPythonでグラフを描画するためのライブラリです。棒グラフ、折れ線グラフ、散布図、ヒストグラムなど、様々な種類のグラフを簡単に作成できます。データ分析の結果を視覚的に表現することで、データの傾向やパターンを把握しやすくなり、より深い洞察を得ることができます。
Matplotlibは、Pythonの標準ライブラリではありませんが、pipを使って簡単にインストールできます。
pip install matplotlib
What is Matplotlib? Why do you need to learn it?
Matplotlib is a Python library for creating graphs and visualizations. It allows you to easily generate various types of charts, such as bar graphs, line graphs, scatter plots, and histograms. By visually representing data analysis results, you can more easily grasp trends and patterns in the data, leading to deeper insights.
Matplotlib isn't part of Python's standard library but can be easily installed using pip:
pip install matplotlib
2. 環境構築と基本的なグラフ描画
まず、Matplotlibを使用するための環境を整えましょう。Jupyter NotebookやGoogle Colaboratoryなどのインタラクティブな環境を使うのがおすすめです。これらの環境では、コードを実行するとすぐにグラフが表示されるため、試行錯誤が容易です。
問題1:シンプルな折れ線グラフを描画する
以下のデータを使って、時間経過に伴う温度変化の折れ線グラフを描画してください。
import matplotlib.pyplot as plt time = [0, 1, 2, 3, 4, 5] temperature = [20, 22, 25, 28, 27, 26] plt.plot(time, temperature) plt.xlabel("時間 (分)") plt.ylabel("温度 (°C)") plt.title("時間経過に伴う温度変化") plt.show()
解説:
import matplotlib.pyplot as plt
: Matplotlibのpyplotモジュールをインポートし、plt
というエイリアスで使用します。これにより、Matplotlibの様々な関数を簡潔に呼び出すことができます。pyplot
はグラフ描画のための主要なインターフェースを提供します。plt.plot(time, temperature)
:time
とtemperature
のリストを使って折れ線グラフを描画します。plt.plot()
関数は、x軸とy軸のデータを引数として受け取り、それらの間の線をプロットします。plt.xlabel()
,plt.ylabel()
,plt.title()
: グラフの軸ラベルとタイトルを設定します。これらの関数は、グラフを理解しやすくするために不可欠です。xlabel()
はx軸のラベルを設定し、ylabel()
はy軸のラベルを設定し、title()
はグラフ全体のタイトルを設定します。plt.show()
: グラフを表示します。この関数は、Matplotlibが生成したグラフを画面に表示するために必要です。
Problem 1: Drawing a Simple Line Graph
Using the following data, draw a line graph showing temperature changes over time.
import matplotlib.pyplot as plt time = [0, 1, 2, 3, 4, 5] temperature = [20, 22, 25, 28, 27, 26] plt.plot(time, temperature) plt.xlabel("Time (minutes)") plt.ylabel("Temperature (°C)") plt.title("Temperature Changes Over Time") plt.show()
Explanation:
import matplotlib.pyplot as plt
: Imports the pyplot module from Matplotlib and usesplt
as an alias. This allows you to call various Matplotlib functions concisely.plt.plot(time, temperature)
: Draws a line graph using the liststime
andtemperature
. Theplt.plot()
function takes x-axis and y-axis data as arguments and plots a line between them.plt.xlabel()
,plt.ylabel()
,plt.title()
: Sets the axis labels and title of the graph. These functions are essential for making the graph understandable.xlabel()
sets the label for the x-axis,ylabel()
sets the label for the y-axis, andtitle()
sets the overall title of the graph.plt.show()
: Displays the graph. This function is necessary to display the graph generated by Matplotlib on the screen.
3. グラフの種類を使いこなす:棒グラフ、散布図、ヒストグラム
Matplotlibには様々な種類のグラフがあります。それぞれの特徴を理解し、適切なグラフを選択することが重要です。データの種類や表現したい内容に応じて最適なグラフを選ぶことで、より効果的に情報を伝えることができます。
問題2:棒グラフを描画する
以下のデータを使って、各商品の売上高の棒グラフを描画してください。
import matplotlib.pyplot as plt products = ['A', 'B', 'C', 'D'] sales = [100, 150, 80, 200] plt.bar(products, sales) plt.xlabel("商品") plt.ylabel("売上高 (円)") plt.title("各商品の売上高") plt.show()
問題3:散布図を描画する
以下のデータを使って、身長と体重の散布図を描画してください。
import matplotlib.pyplot as plt height = [160, 170, 180, 155, 165] weight = [50, 60, 70, 45, 55] plt.scatter(height, weight) plt.xlabel("身長 (cm)") plt.ylabel("体重 (kg)") plt.title("身長と体重の散布図") plt.show()
問題4:ヒストグラムを描画する
以下のデータを使って、テストの点数のヒストグラムを描画してください。
import matplotlib.pyplot as plt import numpy as np scores = np.random.randint(0, 100, 50) # 0から99までのランダムな整数を50個生成 plt.hist(scores, bins=10) # binsはビンの数 plt.xlabel("点数") plt.ylabel("頻度") plt.title("テストの点数のヒストグラム") plt.show()
解説:
plt.bar()
: 棒グラフを描画します。x軸にカテゴリ(商品名など)、y軸に値を指定します。plt.scatter()
: 散布図を描画します。x軸とy軸のそれぞれにデータを指定し、各データポイントを点としてプロットします。plt.hist()
: ヒストグラムを描画します。データの分布を可視化するために使用されます。bins
引数は、ヒストグラムのビンの数を指定します。ビンの数が多いほど、より詳細な分布が表示されますが、ビンの数が少なすぎる場合は、重要なパターンが見落とされる可能性があります。
Problem 2: Drawing a Bar Graph
Using the following data, draw a bar graph showing the sales of each product.
import matplotlib.pyplot as plt products = ['A', 'B', 'C', 'D'] sales = [100, 150, 80, 200] plt.bar(products, sales) plt.xlabel("Product") plt.ylabel("Sales (yen)") plt.title("Sales of Each Product") plt.show()
Problem 3: Drawing a Scatter Plot
Using the following data, draw a scatter plot showing height and weight.
import matplotlib.pyplot as plt height = [160, 170, 180, 155, 165] weight = [50, 60, 70, 45, 55] plt.scatter(height, weight) plt.xlabel("Height (cm)") plt.ylabel("Weight (kg)") plt.title("Scatter Plot of Height and Weight") plt.show()
Problem 4: Drawing a Histogram
Using the following data, draw a histogram showing test scores.
import matplotlib.pyplot as plt import numpy as np scores = np.random.randint(0, 100, 50) # Generate 50 random integers between 0 and 99 plt.hist(scores, bins=10) # bins is the number of bins plt.xlabel("Score") plt.ylabel("Frequency") plt.title("Histogram of Test Scores") plt.show()
Explanation:
plt.bar()
: Draws a bar graph. Specifies categories (e.g., product names) on the x-axis and values on the y-axis.plt.scatter()
: Draws a scatter plot. Specifies data for both the x-axis and y-axis, plotting each data point as a dot.plt.hist()
: Draws a histogram. Used to visualize the distribution of data. Thebins
argument specifies the number of bins in the histogram. A larger number of bins provides more detailed distribution but can obscure important patterns if too few bins are used.
4. グラフをカスタマイズする:色、線種、マーカー
Matplotlibでは、グラフの色、線種、マーカーなどを自由に設定できます。これにより、グラフの見やすさを向上させたり、特定のデータを強調したりすることができます。グラフの見た目を調整することで、より効果的に情報を伝えることができます。
問題5:グラフのスタイルを変更する
問題1の折れ線グラフを、以下の条件で変更してください。
- 線の色を赤にする
- 線の太さを2にする
- マーカーを丸にする
- マーカーの色を青にする
import matplotlib.pyplot as plt time = [0, 1, 2, 3, 4, 5] temperature = [20, 22, 25, 28, 27, 26] plt.plot(time, temperature, color='red', linewidth=2, marker='o', markersize=8, markerfacecolor='blue') plt.xlabel("時間 (分)") plt.ylabel("温度 (°C)") plt.title("時間経過に伴う温度変化") plt.show()
解説:
color
: 線の色を指定します。色の名前('red', 'green', 'blue'など)や16進数カラーコード('#FF0000'など)を使用できます。linewidth
: 線の太さを指定します。数値で指定します。marker
: マーカーの形状を指定します。'o' (丸), 's' (四角), '^' (三角形) など、様々な形状があります。markersize
: マーカーのサイズを指定します。数値で指定します。markerfacecolor
: マーカーの色を指定します。
Problem 5: Changing the Graph Style
Modify Problem 1’s line graph according to the following conditions:
- Change the line color to red.
- Set the line thickness to 2.
- Make the marker a circle.
- Change the marker color to blue.
import matplotlib.pyplot as plt time = [0, 1, 2, 3, 4, 5] temperature = [20, 22, 25, 28, 27, 26] plt.plot(time, temperature, color='red', linewidth=2, marker='o', markersize=8, markerfacecolor='blue') plt.xlabel("Time (minutes)") plt.ylabel("Temperature (°C)") plt.title("Temperature Changes Over Time") plt.show()
Explanation:
color
: Specifies the line color. You can use color names ('red', 'green', 'blue', etc.) or hexadecimal color codes ('#FF0000', etc.).linewidth
: Specifies the line thickness. Specify with a number.marker
: Specifies the shape of the marker. Various shapes are available, such as 'o' (circle), 's' (square), and '^' (triangle).markersize
: Specifies the size of the marker. Specify with a number.markerfacecolor
: Specifies the color of the marker.
5. 複数のグラフを重ねて表示する:凡例、軸の共有
複数のグラフを重ねて表示することで、異なるデータ間の関係性を視覚的に表現することができます。凡例を使用することで、どの線やマーカーがどのデータを表しているかを明確にすることができます。また、軸を共有することで、複数のグラフを比較しやすくなります。
問題6:複数の折れ線グラフを重ねて表示する
以下の2つのデータを使って、時間経過に伴う温度変化と湿度の折れ線グラフを重ねて表示してください。凡例を追加し、軸を共有してください。
import matplotlib.pyplot as plt time = [0, 1, 2, 3, 4, 5] temperature = [20, 22, 25, 28, 27, 26] humidity = [60, 65, 70, 75, 72, 68] plt.plot(time, temperature, label='温度') plt.plot(time, humidity, label='湿度') plt.xlabel("時間 (分)") plt.ylabel("値") plt.title("時間経過に伴う温度と湿度の変化") plt.legend() # 凡例を表示 plt.show()
解説:
label
: 各グラフのラベルを指定します。plt.legend()
: 凡例を表示します。凡例は、各グラフのラベルに基づいて自動的に作成されます。
Problem 6: Displaying Multiple Line Graphs Overlaid
Display the temperature change and humidity line graphs over time using the following two sets of data. Add a legend and share the axes.
import matplotlib.pyplot as plt time = [0, 1, 2, 3, 4, 5] temperature = [20, 22, 25, 28, 27, 26] humidity = [60, 65, 70, 75, 72, 68] plt.plot(time, temperature, label='Temperature') plt.plot(time, humidity, label='Humidity') plt.xlabel("Time (minutes)") plt.ylabel("Value") plt.title("Changes in Temperature and Humidity Over Time") plt.legend() # Display the legend plt.show()
Explanation:
label
: Specifies a label for each graph.plt.legend()
: Displays the legend. The legend is automatically created based on the labels of each graph.
6. サブプロットを作成する:複数のグラフを1つの図に表示する
サブプロットを使用することで、1つの図の中に複数のグラフを並べて表示することができます。これにより、異なるデータ間の関係性を比較したり、複雑な情報を整理して表現したりすることができます。
問題7:サブプロットを作成する
問題2の棒グラフと問題3の散布図を、1つの図に横並びで表示してください。
import matplotlib.pyplot as plt # 棒グラフのデータ products = ['A', 'B', 'C', 'D'] sales = [100, 150, 80, 200] # 散布図のデータ height = [160, 170, 180, 155, 165] weight = [50, 60, 70, 45, 55] # サブプロットを作成 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4)) # 1行2列のサブプロット # 棒グラフを描画 ax1.bar(products, sales) ax1.set_xlabel("商品") ax1.set_ylabel("売上高 (円)") ax1.set_title("各商品の売上高") # 散布図を描画 ax2.scatter(height, weight) ax2.set_xlabel("身長 (cm)") ax2.set_ylabel("体重 (kg)") ax2.set_title("身長と体重の散布図") plt.tight_layout() # レイアウトを調整 plt.show()
解説:
plt.subplots(1, 2)
: 1行2列のサブプロットを作成します。返り値は、FigureオブジェクトとAxesオブジェクトのタプルです。ax1
,ax2
: 各サブプロットに対応するAxesオブジェクトです。これらのオブジェクトを使って、各サブプロットにグラフを描画します。plt.tight_layout()
: サブプロット間の間隔を自動的に調整し、ラベルなどが重ならないようにします。
Problem 7: Creating Subplots
Display Problem 2’s bar graph and Problem 3’s scatter plot side by side in a single figure.
import matplotlib.pyplot as plt # Bar graph data products = ['A', 'B', 'C', 'D'] sales = [100, 150, 80, 200] # Scatter plot data height = [160, 170, 180, 155, 165] weight = [50, 60, 70, 45, 55] # Create subplots fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4)) # 1 row and 2 columns of subplots # Draw the bar graph ax1.bar(products, sales) ax1.set_xlabel("Product") ax1.set_ylabel("Sales (yen)") ax1.set_title("Sales of Each Product") # Draw the scatter plot ax2.scatter(height, weight) ax2.set_xlabel("Height (cm)") ax2.set_ylabel("Weight (kg)") ax2.set_title("Scatter Plot of Height and Weight") plt.tight_layout() # Adjust layout plt.show()
Explanation:
plt.subplots(1, 2)
: Creates a subplot with 1 row and 2 columns. The return value is a tuple containing the Figure object and Axes objects.ax1
,ax2
: Axes objects corresponding to each subplot. Use these objects to draw graphs on each subplot.plt.tight_layout()
: Automatically adjusts spacing between subplots so that labels do not overlap.
7. グラフにテキストや注釈を追加する:annotate()
グラフにテキストや注釈を追加することで、特定のデータポイントについて説明したり、重要な情報を強調したりすることができます。
問題8:グラフに注釈を追加する
問題3の散布図に、最も身長が高く体重が軽い点に「外れ値」という注釈を追加してください。
import matplotlib.pyplot as plt height = [160, 170, 180, 155, 165] weight = [50, 60, 70, 45, 55] plt.scatter(height, weight) plt.xlabel("身長 (cm)") plt.ylabel("体重 (kg)") plt.title("身長と体重の散布図") # 外れ値の座標 outlier_x = 180 outlier_y = 70 # 注釈を追加 plt.annotate('外れ値', xy=(outlier_x, outlier_y), xytext=(outlier_x + 5, outlier_y - 5), arrowprops=dict(facecolor='black', shrink=0.05)) plt.show()
解説:
plt.annotate()
: 注釈を追加します。xy
: 注釈するデータポイントの座標を指定します。xytext
: 注釈テキストの位置を指定します。arrowprops
: 矢印のプロパティ(色、サイズなど)を指定します。
Problem 8: Adding Annotations to a Graph
Add an annotation labeled "Outlier" to the point with the greatest height and lightest weight in Problem 3’s scatter plot.
import matplotlib.pyplot as plt height = [160, 170, 180, 155, 165] weight = [50, 60, 70, 45, 55] plt.scatter(height, weight) plt.xlabel("Height (cm)") plt.ylabel("Weight (kg)") plt.title("Scatter Plot of Height and Weight") # Coordinates of the outlier outlier_x = 180 outlier_y = 70 # Add an annotation plt.annotate('Outlier', xy=(outlier_x, outlier_y), xytext=(outlier_x + 5, outlier_y - 5), arrowprops=dict(facecolor='black', shrink=0.05)) plt.show()
Explanation:
plt.annotate()
: Adds an annotation.xy
: Specifies the coordinates of the data point to be annotated.xytext
: Specifies the position of the annotation text.arrowprops
: Specifies the properties (color, size, etc.) of the arrow.
8. グラフをファイルに保存する:savefig()
Matplotlibでは、作成したグラフを画像ファイルとして保存することができます。これにより、グラフをレポートやプレゼンテーションで使用したり、Webサイトに公開したりすることができます。
問題9:グラフをファイルに保存する
問題1の折れ線グラフをPNG形式で「temperature_graph.png」という名前で保存してください。
import matplotlib.pyplot as plt time = [0, 1, 2, 3, 4, 5] temperature = [20, 22, 25, 28, 27, 26] plt.plot(time, temperature) plt.xlabel("時間 (分)") plt.ylabel("温度 (°C)") plt.title("時間経過に伴う温度変化") plt.savefig('temperature_graph.png') # ファイルに保存 plt.show()
解説:
plt.savefig()
: グラフをファイルに保存します。引数には、保存するファイル名を指定します。ファイル形式は、拡張子によって自動的に決定されます。
Problem 9: Saving a Graph to a File
Save Problem 1’s line graph as a PNG file named "temperature_graph.png."
import matplotlib.pyplot as plt time = [0, 1, 2, 3, 4, 5] temperature = [20, 22, 25, 28, 27, 26] plt.plot(time, temperature) plt.xlabel("Time (minutes)") plt.ylabel("Temperature (°C)") plt.title("Changes in Temperature Over Time") plt.savefig('temperature_graph.png') # Save to file plt.show()
Explanation:
plt.savefig()
: Saves the graph to a file. The argument is the filename to save to. The file format is automatically determined by the extension.
9. より複雑なグラフを描画する:等高線図、3Dグラフ
Matplotlibは、等高線図や3Dグラフなど、より複雑なグラフも描画することができます。これらのグラフを使用することで、多次元データを視覚的に表現したり、複雑な現象をモデル化したりすることができます。
問題10:簡単な等高線図を描画する
import matplotlib.pyplot as plt import numpy as np # データの生成 x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = np.sin(np.sqrt(X**2 + Y**2)) # 等高線図の描画 plt.contourf(X, Y, Z, cmap='viridis') # カラーマップを指定 plt.colorbar() #カラーバーを表示 plt.xlabel("x") plt.ylabel("y") plt.title("等高線図") plt.show()
解説:
np.linspace()
: 指定された範囲で等間隔の数値配列を生成します。np.meshgrid()
: 2次元グリッドを作成します。plt.contourf()
: 等高線図を描画します。cmap
引数でカラーマップを指定できます。
Problem 10: Drawing a Simple Contour Plot
import matplotlib.pyplot as plt import numpy as np # Generate data x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = np.sin(np.sqrt(X**2 + Y**2)) # Draw the contour plot plt.contourf(X, Y, Z, cmap='viridis') # Specify a color map plt.colorbar() #Display the colorbar plt.xlabel("x") plt.ylabel("y") plt.title("Contour Plot") plt.show()
Explanation:
np.linspace()
: Generates an array of evenly spaced values within a specified range.np.meshgrid()
: Creates a 2D grid.plt.contourf()
: Draws a contour plot. Thecmap
argument specifies the color map.
まとめ
本記事では、Matplotlibを使ったグラフ描画練習問題10選を紹介しました。これらの問題を解くことで、Matplotlibの基本的な使い方から応用的な使い方までを学ぶことができます。ぜひ、これらの問題を参考に、Matplotlibスキルを向上させてください。
参照先:
- Matplotlib公式ドキュメント: https://matplotlib.org/
- Python Graph Gallery: https://python-graph-gallery.com/
これらのリソースを活用することで、さらにMatplotlibの知識を深めることができます。頑張ってください!
Conclusion:
This article has introduced 10 practice problems for drawing graphs using Matplotlib. By solving these problems, you can learn the basic and advanced usage of Matplotlib. Please refer to these problems and improve your Matplotlib skills. Good luck!