基本プロット作成
Matplotlibを用いた基本的なプロット作成手順:
import numpy as np
import matplotlib.pyplot as plt
x_values = np.linspace(0, 2*np.pi, 100)
sine_wave = np.sin(x_values)
cosine_wave = np.cos(x_values)
plt.title("三角関数の比較")
plt.plot(x_values, sine_wave)
plt.plot(x_values, cosine_wave)
plt.show()
棒グラフの作成
縦型・横型棒グラフの実装例:
values = [35, 70, 25, 60]
plt.bar(range(len(values)), values)
plt.show()
plt.barh(range(len(values)), values)
plt.show()
複合棒グラフ
グループ化と積み上げの実装:
dataset = [[15, 30, 45, 20],
[10, 35, 40, 25],
[20, 25, 35, 30]]
x_positions = np.arange(4)
# グループ化
plt.bar(x_positions - 0.2, dataset[0], width=0.2, label='A')
plt.bar(x_positions, dataset[1], width=0.2, label='B')
plt.bar(x_positions + 0.2, dataset[2], width=0.2, label='C')
plt.legend()
# 積み上げ
plt.bar(x_positions, dataset[0], color='blue')
plt.bar(x_positions, dataset[1], color='green', bottom=dataset[0])
plt.bar(x_positions, dataset[2], color='red', bottom=np.array(dataset[0]) + np.array(dataset[1]))
散布図の作成
num_points = 50
x_data = np.random.rand(num_points)
y_data = np.random.rand(num_points)
colors = np.random.rand(num_points)
sizes = 300 * np.random.rand(num_points)**2
plt.scatter(x_data, y_data, c=colors, s=sizes, alpha=0.6)
plt.colorbar()
ヒストグラムと箱ひげ図
# ヒストグラム
data_samples = np.random.randn(1000)
plt.hist(data_samples, bins=30, edgecolor='black')
# 箱ひげ図
data_matrix = np.random.randint(20, 100, size=(30, 3))
plt.boxplot(data_matrix, labels=['A', 'B', 'C'])
plt.hlines(y=np.mean(data_matrix, axis=0)[1], xmin=0, xmax=3, colors='r')
サブプロットの活用
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
ax0, ax1, ax2, ax3 = axes.flatten()
ax0.plot(data_samples)
ax0.set_title("データ分布")
ax1.hist(data_samples, bins=20, alpha=0.7)
ax2.scatter(x_data, y_data)
ax3.boxplot(data_matrix)
plt.tight_layout()
Seabornによる可視化
import seaborn as sns
iris = sns.load_dataset("iris")
# 分布プロット
sns.histplot(iris['sepal_length'], kde=True)
# 関係性の可視化
sns.jointplot(x='sepal_length', y='sepal_width', data=iris)
# ペアプロット
sns.pairplot(iris)
Pyechartsの応用
from pyecharts.charts import Bar
categories = ['A', 'B', 'C', 'D', 'E']
values = [120, 150, 90, 80, 200]
bar_chart = Bar()
bar_chart.add_xaxis(categories)
bar_chart.add_yaxis("値", values)
bar_chart.render("bar_chart.html")
高度なカスタマイズ
# 軸の調整
ax = plt.gca()
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
# テーマ設定
plt.style.use('ggplot')
# 3Dプロット
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x_data, y_data, np.random.rand(num_points))