matplotlib-円グラフの作成メモ

目次

円グラフの作成

目的

機械学習やビッグデータの解析では,大量にある多次元データを様々な側面から見る必要がある.ここでは,matplotlibを用いた円グラフの作成方法を学ぶ.

説明

円グラフの描画

まずは簡単な円グラフを描画してみよう.

from numpy.random import default_rng
import matplotlib.pyplot as plt
def main():
    rg = default_rng(seed=0)
    students_count = 280
    scores = rg.normal(65.9, 10.8, students_count)
    s_count = (90 <= scores).sum()
    a_count = ((80 <= scores) & (scores < 90)).sum()
    b_count = ((70 <= scores) & (scores < 80)).sum()
    c_count = ((60 <= scores) & (scores < 70)).sum()
    d_count = ((50 <= scores) & (scores < 60)).sum()
    e_count = (scores < 50).sum()
    fig = plt.figure(figsize=plt.figaspect(1.0))
    ax = fig.add_subplot()
    ax.pie([s_count, a_count, b_count, c_count, d_count, e_count])
    plt.show()
if __name__ == '__main__':
    main()

6行目から8行目で,280名の学生のある科目のテストの点数からなる配列を作っている.10行目で90点以上の点数をとった学生数を,11行目で80点以上90点未満の点数をとった学生数を求めている.以下同様に,12行目から15行目までで,各範囲の点数をとった学生数を求めている.19行目のように,axオブジェクトのpieメソッドを,円グラフとして表したい数からなるリストを引数として呼び出すと,円グラフを作成することができる.

凡例・タイトルの表示

円グラフに凡例とタイトルを指定するには,以下のようにすればよい.

from numpy.random import default_rng
import matplotlib.pyplot as plt
def main():
    rg = default_rng(seed=0)
    students_count = 280
    scores = rg.normal(65.9, 10.8, students_count)
    labels = ['S', 'A', 'B', 'C', 'D', 'E']
    s_count = (90 <= scores).sum()
    a_count = ((80 <= scores) & (scores < 90)).sum()
    b_count = ((70 <= scores) & (scores < 80)).sum()
    c_count = ((60 <= scores) & (scores < 70)).sum()
    d_count = ((50 <= scores) & (scores < 60)).sum()
    e_count = (scores < 50).sum()
    fig = plt.figure(figsize=plt.figaspect(1.0))
    ax = fig.add_subplot()
    ax.pie([s_count, a_count, b_count, c_count, d_count, e_count])
    ax.legend(labels, loc='best')
    ax.set_title('Fig.1: Student grades.')
    plt.show()
if __name__ == '__main__':
    main()

10行目で凡例として表示する文字列からなるリストを作成し,21行目のように,axオブジェクトのlegendメソッドを,作成したリストを引数として呼び出すと,円グラフに凡例をつけることができる.また,タイトルの指定の仕方はこれまでと同様である.

開始位置と描画方向の指定

上の実行結果からわかるように,この円グラフは3時の位置から開始し,半時計回りに描画されている.これを12時の位置から開始し,時計回りに描画するには,以下のようにすればよい.

from numpy.random import default_rng
import matplotlib.pyplot as plt
def main():
    rg = default_rng(seed=0)
    students_count = 280
    scores = rg.normal(65.9, 10.8, students_count)
    labels = ['S', 'A', 'B', 'C', 'D', 'E']
    s_count = (90 <= scores).sum()
    a_count = ((80 <= scores) & (scores < 90)).sum()
    b_count = ((70 <= scores) & (scores < 80)).sum()
    c_count = ((60 <= scores) & (scores < 70)).sum()
    d_count = ((50 <= scores) & (scores < 60)).sum()
    e_count = (scores < 50).sum()
    fig = plt.figure(figsize=plt.figaspect(1.0))
    ax = fig.add_subplot()
    ax.pie([s_count, a_count, b_count, c_count, d_count, e_count], startangle=90, counterclock=False)
    ax.legend(labels, loc='best')
    ax.set_title('Fig.1: Student grades.')
    plt.show()
if __name__ == '__main__':
    main()

20行目のように,pieメソッドのキーワード引数startangleに90度と指定すると,デフォルトの開始位置から半時計回り(デフォルトの描画方向)に90度の位置から描画を開始できる.また,キーワード引数counterclockにFalseを指定すると,時計回りに描画することができる.

ラベルの指定

凡例としてではなく,円グラフの周囲にラベルを表示するには,pieメソッドのキーワード引数labelsを使用すればよい.

from numpy.random import default_rng
import matplotlib.pyplot as plt
def main():
    rg = default_rng(seed=0)
    students_count = 280
    scores = rg.normal(65.9, 10.8, students_count)
    labels = ['S', 'A', 'B', 'C', 'D', 'E']
    s_count = (90 <= scores).sum()
    a_count = ((80 <= scores) & (scores < 90)).sum()
    b_count = ((70 <= scores) & (scores < 80)).sum()
    c_count = ((60 <= scores) & (scores < 70)).sum()
    d_count = ((50 <= scores) & (scores < 60)).sum()
    e_count = (scores < 50).sum()
    fig = plt.figure(figsize=plt.figaspect(1.0))
    ax = fig.add_subplot()
    ax.pie([s_count, a_count, b_count, c_count, d_count, e_count], labels=labels, startangle=90, counterclock=False)
    ax.set_title('Fig.1: Student grades.')
    plt.show()
if __name__ == '__main__':
    main()

各データの割合をパーセント表示

各データの割合をパーセント表示することができる.

from numpy.random import default_rng
import matplotlib.pyplot as plt
def main():
    rg = default_rng(seed=0)
    students_count = 280
    scores = rg.normal(65.9, 10.8, students_count)
    labels = ['S', 'A', 'B', 'C', 'D', 'E']
    s_count = (90 <= scores).sum()
    a_count = ((80 <= scores) & (scores < 90)).sum()
    b_count = ((70 <= scores) & (scores < 80)).sum()
    c_count = ((60 <= scores) & (scores < 70)).sum()
    d_count = ((50 <= scores) & (scores < 60)).sum()
    e_count = (scores < 50).sum()
    fig = plt.figure(figsize=plt.figaspect(1.0))
    ax = fig.add_subplot()
    ax.pie([s_count, a_count, b_count, c_count, d_count, e_count], autopct='%.1f%%', startangle=90, counterclock=False)
    ax.legend(labels, loc='best')
    ax.set_title('Fig.1: Student grades.')
    plt.show()
if __name__ == '__main__':
    main()

20行目のように,pieメソッドのキーワード引数autopctに’%.1f%%’と指定すると,小数点以下1桁までの浮動小数点数として各データの割合をパーセント表示することができる.記述のルールはf文字列のフォーマット指定と同じである.

この例では,パーセント表示の一部が重複してしまっている.表示位置を変更するには,以下のようにすればよい.

from numpy.random import default_rng
import matplotlib.pyplot as plt
def main():
    rg = default_rng(seed=0)
    students_count = 280
    scores = rg.normal(65.9, 10.8, students_count)
    labels = ['S', 'A', 'B', 'C', 'D', 'E']
    s_count = (90 <= scores).sum()
    a_count = ((80 <= scores) & (scores < 90)).sum()
    b_count = ((70 <= scores) & (scores < 80)).sum()
    c_count = ((60 <= scores) & (scores < 70)).sum()
    d_count = ((50 <= scores) & (scores < 60)).sum()
    e_count = (scores < 50).sum()
    fig = plt.figure(figsize=plt.figaspect(1.0))
    ax = fig.add_subplot()
    ax.pie([s_count, a_count, b_count, c_count, d_count, e_count], autopct='%1.1f%%', pctdistance=1.1, startangle=90, counterclock=False)
    ax.legend(labels, loc='lower right')
    ax.set_title('Fig.1: Student grades.')
    plt.show()
if __name__ == '__main__':
    main()

20行目のように,pieメソッドのキーワード引数pctdistanceに数値を指定することで,パーセント表示の位置を変更できる.0が円の中心を1が円周を表しており,20行目のように1.1と指定することで,円の少し外側に表示位置を変更している.

各領域の色の指定

円グラフの各領域の色を指定するには,以下のようにすればよい.

from numpy.random import default_rng
import matplotlib.pyplot as plt
def main():
    rg = default_rng(seed=0)
    students_count = 280
    scores = rg.normal(65.9, 10.8, students_count)
    labels = ['S', 'A', 'B', 'C', 'D', 'E']
    colors = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow']
    s_count = (90 <= scores).sum()
    a_count = ((80 <= scores) & (scores < 90)).sum()
    b_count = ((70 <= scores) & (scores < 80)).sum()
    c_count = ((60 <= scores) & (scores < 70)).sum()
    d_count = ((50 <= scores) & (scores < 60)).sum()
    e_count = (scores < 50).sum()
    fig = plt.figure(figsize=plt.figaspect(1.0))
    ax = fig.add_subplot()
    ax.pie([s_count, a_count, b_count, c_count, d_count, e_count], colors=colors, autopct='%1.1f%%', pctdistance=1.1, startangle=90, counterclock=False)
    ax.legend(labels, loc='lower right')
    ax.set_title('Fig.1: Student grades.')
    plt.show()
if __name__ == '__main__':
    main()

11行目で各領域の色を表す文字列からなるリストを作成し,21行目のpieメソッドのキーワード引数colorsで色のリストを指定している.

各領域の輝度の指定

円グラフをグレースケールとして作成したい場合には,以下のようにすればよい.

from numpy.random import default_rng
import matplotlib.pyplot as plt
def main():
    rg = default_rng(seed=0)
    students_count = 280
    scores = rg.normal(65.9, 10.8, students_count)
    labels = ['S', 'A', 'B', 'C', 'D', 'E']
    brightness = ['0.15', '0.3', '0.45', '0.6', '0.75', '0.9']
    s_count = (90 <= scores).sum()
    a_count = ((80 <= scores) & (scores < 90)).sum()
    b_count = ((70 <= scores) & (scores < 80)).sum()
    c_count = ((60 <= scores) & (scores < 70)).sum()
    d_count = ((50 <= scores) & (scores < 60)).sum()
    e_count = (scores < 50).sum()
    fig = plt.figure(figsize=plt.figaspect(1.0))
    ax = fig.add_subplot()
    ax.pie([s_count, a_count, b_count, c_count, d_count, e_count], colors=brightness, autopct='%1.1f%%', pctdistance=1.1, startangle=90, counterclock=False)
    ax.legend(labels, loc='lower right')
    ax.set_title('Fig.1: Student grades.')
    plt.show()
if __name__ == '__main__':
    main()

11行目で各領域の輝度を表す文字列からなるリストを作成している.0が最も暗く,1が最も明るい画素を表している.21行目のように,pieメソッドのキーワード引数colorsで輝度のリストを指定することで,グレースケールの円グラフを作成できる.

各領域の境界線の指定

円グラフの各領域の境界線を表示するには,以下のようにすればよい.

from numpy.random import default_rng
import matplotlib.pyplot as plt
def main():
    rg = default_rng(seed=0)
    students_count = 280
    scores = rg.normal(65.9, 10.8, students_count)
    labels = ['S', 'A', 'B', 'C', 'D', 'E']
    brightness = ['0.15', '0.3', '0.45', '0.6', '0.75', '0.9']
    s_count = (90 <= scores).sum()
    a_count = ((80 <= scores) & (scores < 90)).sum()
    b_count = ((70 <= scores) & (scores < 80)).sum()
    c_count = ((60 <= scores) & (scores < 70)).sum()
    d_count = ((50 <= scores) & (scores < 60)).sum()
    e_count = (scores < 50).sum()
    fig = plt.figure(figsize=plt.figaspect(1.0))
    ax = fig.add_subplot()
    ax.pie([s_count, a_count, b_count, c_count, d_count, e_count], wedgeprops={'linewidth': 1, 'edgecolor': 'black'}, colors=brightness, autopct='%1.1f%%', pctdistance=1.1, startangle=90, counterclock=False)
    ax.legend(labels, loc='lower right')
    ax.set_title('Fig.1: Student grades.')
    plt.show()
if __name__ == '__main__':
    main()

21行目のように,pieメソッドのキーワード引数wedgepropsに辞書として境界線の太さと色を指定することができる.辞書のキーlinewidthが線の太さを,キーedgecolorが線の色を表している.

参考サイト

http://makotomurakami.com/blog/2020/04/03/4614/

python-pptx画像書き込み

import plotly.graph_objs as go
import plotly.io as pio
from pptx import Presentation
from pptx.util import Inches
from io import BytesIO
# サンプルのplotlyグラフを作成
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 1, 2])])
#fig.update_layout(title='グラフのタイトル', legend_font_family='メイリオ')
fig.update_layout(title='グラフのタイトル', legend_font_family='MSゴシック')
# plotlyグラフを画像に変換
img_bytes = pio.to_image(fig, format='png')
# BytesIOを使用して画像データをバッファに保持
img_buffer = BytesIO(img_bytes)
# 新しいプレゼンテーションを作成
prs = Presentation()
# 新しいスライドを追加
slide = prs.slides.add_slide(prs.slide_layouts[5])  # 5は白紙のスライドレイアウト
# 画像をスライドに追加
#left = Inches(1)
#top = Inches(2)
#width = Inches(5)
#height = Inches(4)
#pic = slide.shapes.add_picture(img_buffer, left, top, width, height)
pic = slide.shapes.add_picture(img_buffer, Inches(1), Inches(2), Inches(7), Inches(5))
# プレゼンテーションを保存
prs.save("example_with_plotly.pptx")
# バッファを閉じる
img_buffer.close()

その2

import matplotlib.pyplot as plt
from pptx import Presentation
from pptx.util import Inches
from io import BytesIO
# サンプルのMatplotlibグラフを作成
plt.plot([1, 2, 3], [4, 1, 2])
plt.xlabel("X軸")
plt.ylabel("Y軸")
plt.title("Matplotlibグラフ")
# グラフを画像に変換
img_buffer = BytesIO()
plt.savefig(img_buffer, format='png')
img_buffer.seek(0)
plt.close()
# 新しいプレゼンテーションを作成
prs = Presentation()
# 新しいスライドを追加
slide = prs.slides.add_slide(prs.slide_layouts[5])  # 5は白紙のスライドレイアウト
# 画像をスライドに追加
left = Inches(1)
top = Inches(2)
width = Inches(5)
height = Inches(4)
pic = slide.shapes.add_picture(img_buffer, left, top, width, height)
# プレゼンテーションを保存
prs.save("example_with_matplotlib.pptx")
# バッファを閉じる
img_buffer.close()

その3

import plotly.graph_objs as go
from pptx import Presentation
from pptx.util import Inches
from pptx.enum.text import PP_PARAGRAPH_ALIGNMENT
# サンプルのplotly表データを作成
data = [
    go.Table(
        header=dict(values=['列1', '列2']),
        cells=dict(values=[[1, 2, 3], [4, 5, 6]])
    )
]
# 新しいプレゼンテーションを作成
prs = Presentation()
# 新しいスライドを追加
slide = prs.slides.add_slide(prs.slide_layouts[5])  # 5は白紙のスライドレイアウト
# テーブルをスライドに追加
left = Inches(1)
top = Inches(2)
width = Inches(5)
height = Inches(2)
table = slide.shapes.add_table(rows=3, cols=3, left=left, top=top, width=width, height=height)
#table.fill.solid()
#table.fill.fore_color.rgb = (255, 255, 255)
# ヘッダーを追加
for col, header_text in enumerate(data[0]['header']['values']):
    cell = table.table.cell(0, col)
    cell.text = header_text
    cell.text_frame.paragraphs[0].alignment = PP_PARAGRAPH_ALIGNMENT.CENTER
# データ行を追加
for row, row_data in enumerate(data[0]['cells']['values']):
    for col, cell_value in enumerate(row_data):
        cell = table.table.cell(row + 1, col)
        cell.text = str(cell_value)
        cell.text_frame.paragraphs[0].alignment = PP_PARAGRAPH_ALIGNMENT.CENTER
# プレゼンテーションを保存
prs.save("example_with_plotly_table.pptx")

その4

from pptx import Presentation
from pptx.util import Inches
from pptx.enum.text import PP_PARAGRAPH_ALIGNMENT
from pptx.dml.color import RGBColor
# 新しいプレゼンテーションを作成
prs = Presentation()
# スライドを追加
slide = prs.slides.add_slide(prs.slide_layouts[5])  # 空白スライド
# 表を作成
rows = 3
cols = 3
left = Inches(1)
top = Inches(2)
width = Inches(6)
height = Inches(2)
table = slide.shapes.add_table(rows, cols, left, top, width, height).table
# セル結合
table.cell(0, 0).merge(table.cell(1, 0))
# セルにテキストを挿入
cell = table.cell(0, 0)
cell.text = '値はありませんでした。'
# セルのスタイルを設定
cell.text_frame.paragraphs[0].alignment = PP_PARAGRAPH_ALIGNMENT.CENTER
cell.text_frame.font.size = Inches(0.2)
cell.fill.solid()
cell.fill.fore_color.rgb = RGBColor(217, 217, 217)  # グレーのセル色
# プレゼンテーションを保存
prs.save('table_example.pptx')

その5

from pptx import Presentation
from pptx.util import Inches
# 新しいプレゼンテーションを作成
prs = Presentation()
# スライドを追加
slide = prs.slides.add_slide(prs.slide_layouts[5])  # 空白スライド
# 表データを準備
data = [
    ['Value 1', 'Value 2', 'Value 3'],
    ['', '', ''],
    ['', '', ''],
    ['Value 4', 'Value 5', 'Value 6']
]
# 表を作成
rows = len(data)
cols = len(data[0])
left = Inches(1)
top = Inches(2)
width = Inches(6)
height = Inches(2)
table = slide.shapes.add_table(rows, cols, left, top, width, height).table
# 表データをセルに挿入
for row in range(rows):
    for col in range(cols):
        cell = table.cell(row, col)
        cell.text = data[row][col]
# 空行を見つけてセル結合
for row in range(1, rows):
    is_empty_row = all(cell.text == '' for cell in table.row_cells(row))
    if is_empty_row:
        for cell in table.row_cells(row):
            cell._tc.set_attribute('rowSpan', '2')
        table.cell(row + 1, 0).text = '値はありませんでした。'
        for col in range(1, cols):
            table.cell(row + 1, col).text = ''
            table.cell(row + 1, col)._tc.set_attribute('vMerge', '1')
# プレゼンテーションを保存
prs.save('merged_table.pptx')

その6

from pptx import Presentation
from pptx.util import Inches
# 新しいプレゼンテーションを作成
prs = Presentation()
# スライドを追加
slide = prs.slides.add_slide(prs.slide_layouts[5])  # 空のスライド
# 表を作成
rows = 3
cols = 3
table = slide.shapes.add_table(rows, cols, Inches(1), Inches(2), Inches(8), Inches(4)).table
# 表のヘッダーを設定
for i in range(cols):
    cell = table.cell(0, i)
    cell.text = f'Header {i+1}'
# 新しい行を追加
new_row = table.add_row().cells
new_row[0].text = 'New'
new_row[1].text = 'Row'
new_row[2].text = 'Added'
# プレゼンテーションを保存
prs.save('table_example.pptx')

その7

from pptx import Presentation
from pptx.util import Inches
def add_row_to_table_if_not_exists(table, row_index):
    while len(table.rows) <= row_index:
        table.add_row()
# 新しいプレゼンテーションを作成
prs = Presentation()
# スライドを追加
slide = prs.slides.add_slide(prs.slide_layouts[5])  # 空のスライド
# 表を作成
rows = 3
cols = 3
table = slide.shapes.add_table(rows, cols, Inches(1), Inches(2), Inches(8), Inches(4)).table
# 表のヘッダーを設定
for i in range(cols):
    cell = table.cell(0, i)
    cell.text = f'Header {i+1}'
# 行が存在しない場合に新しい行を追加
target_row_index = 4  # 追加したい行のインデックス
add_row_to_table_if_not_exists(table, target_row_index)
target_row = table.rows[target_row_index].cells
target_row[0].text = 'New'
target_row[1].text = 'Row'
target_row[2].text = 'Added'
# プレゼンテーションを保存
prs.save('table_with_dynamic_row.pptx')

その8

もちろんです。PythonでJSONファイルを読み込み、その情報を使ってPython-pptxでスライドを制御するプログラムの例を以下に示します。 JSONファイル (data.json):

json
{
    "slides": [
        {
            "title": "Slide 1",
            "content": [
                "Point 1",
                "Point 2",
                "Point 3"
            ]
        },
        {
            "title": "Slide 2",
            "content": [
                "Item A",
                "Item B",
                "Item C"
            ]
        }
    ]
}

Pythonプログラム:

python
import json
from pptx import Presentation
from pptx.util import Inches
# JSONファイルを読み込む
with open('data.json', 'r') as json_file:
    data = json.load(json_file)
# 新しいプレゼンテーションを作成
prs = Presentation()
# JSONデータからスライドを作成
for slide_data in data['slides']:
    slide = prs.slides.add_slide(prs.slide_layouts[1])  # タイトルとコンテンツのスライド
    title = slide.shapes.title
    title.text = slide_data['title']
    left = Inches(1)
    top = Inches(2)
    width = Inches(8)
    height = Inches(4)
    content_box = slide.shapes.add_textbox(left, top, width, height)
    content_frame = content_box.text_frame
    for point in slide_data['content']:
        p = content_frame.add_paragraph()
        p.text = point
# プレゼンテーションを保存
prs.save('output_presentation.pptx')

このコードは、JSONファイルからスライドのタイトルとコンテンツ情報を取得し、Python-pptxを使用してプレゼンテーションを生成する例です。JSONファイルを編集して必要な情報を追加または変更し、スライドの構造や内容をカスタマイズできます。

その9

from pptx import Presentation
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
def convert_pptx_to_pdf(input_pptx, output_pdf):
    prs = Presentation(input_pptx)
    pdf_canvas = canvas.Canvas(output_pdf, pagesize=letter)
    for slide in prs.slides:
        pdf_canvas.showPage()
        pdf_canvas.drawString(100, 100, slide.name)  # スライド名を追加できます
        pdf_canvas.drawImage("slide.png", 0, 0, width=letter[0], height=letter[1])  # スライドを画像として追加します
    pdf_canvas.save()
if __name__ == "__main__":
    input_pptx = "input.pptx"  # 変換したいPowerPointファイルのパス
    output_pdf = "output.pdf"  # 保存するPDFファイルのパス
    convert_pptx_to_pdf(input_pptx, output_pdf)

その10

from pptx import Presentation
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
def convert_pptx_to_pdf(input_pptx, output_pdf):
    # PowerPointファイルを開く
    presentation = Presentation(input_pptx)
    # PDFファイルを作成
    pdf_canvas = canvas.Canvas(output_pdf, pagesize=letter)
    # 各スライドをPDFに描画
    for slide in presentation.slides:
        pdf_canvas.showPage()
        pdf_canvas.drawImage(slide.get_image(), 0, 0, width=letter[0], height=letter[1])
    # PDFファイルをクローズ
    pdf_canvas.save()
if __name__ == "__main__":
    input_pptx_file = "input.pptx"  # PowerPointファイルのパス
    output_pdf_file = "output.pdf"  # 出力PDFファイルのパス
    convert_pptx_to_pdf(input_pptx_file, output_pdf_file)

その11

import plotly.graph_objects as go

# サンプルデータ(データは適宜置き換えてください)
categories = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"]
values = [30, 25, 20, 15, 10, 5, 4, 3, 2, 1, 1]
total_values = sum(values)

# トップ10のデータとそれ以下のデータに分割
top_10_categories = categories[:10]
top_10_values = values[:10]
remaining_categories = categories[10:]
remaining_values = values[10:]

# トップ10のデータに対する円グラフを作成
fig = go.Figure()
fig.add_trace(
    go.Pie(
        labels=top_10_categories,
        values=top_10_values,
        textinfo="label+percent",
        title="Top 10 Categories",
    )
)

# トップ10以外のデータの合計値を計算
remaining_value = sum(remaining_values)

# トップ10以外のデータの割合を表示しない
if remaining_value > 0:
    fig.add_trace(
        go.Pie(
            labels=["Others"],
            values=[remaining_value],
            textinfo="none",
            title="",
        )
    )

# グラフを表示
fig.show()

その12

import plotly.express as px

# サンプルデータ(データは適宜置き換えてください)
data = [
    {"Category": "A", "Value": 30},
    {"Category": "B", "Value": 25},
    {"Category": "C", "Value": 20},
    {"Category": "D", "Value": 15},
    {"Category": "E", "Value": 10},
    {"Category": "F", "Value": 5},
    {"Category": "G", "Value": 4},
    {"Category": "H", "Value": 3},
    {"Category": "I", "Value": 2},
    {"Category": "J", "Value": 1},
    {"Category": "K", "Value": 1},
    # ここにさらにデータを追加
]

# データを降順にソート
data.sort(key=lambda x: x["Value"], reverse=True)

# トップ10のデータとそれ以下のデータに分割
top_10_data = data[:10]
remaining_data = data[10:]

# トップ10のデータに対する円グラフを作成
fig = px.pie(top_10_data, values="Value", names="Category", title="Top 10 Categories")
 
# トップ10以外のデータの合計値を計算
remaining_value = sum(item["Value"] for item in remaining_data)

# トップ10以外のデータの割合を表示しない
if remaining_value > 0:
    fig.add_trace(
        px.pie(
            [{"Category": "Others", "Value": remaining_value}],
            values="Value",
            names="Category",
            title="",
        ).data[0]
    )

# グラフを表示
fig.show()

その13

import plotly.graph_objects as go

# サンプルデータ(データは適宜置き換えてください)
categories = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"]
values = [30, 25, 20, 15, 10, 5, 4, 3, 2, 1, 1]

# データを降順にソート
sorted_data = sorted(zip(categories, values), key=lambda x: x[1], reverse=True)

# トップ10のラベルと値を取得
top_10_labels, top_10_values = zip(*sorted_data[:10])

# トップ10のデータに対する円グラフを作成
fig = go.Figure(data=[go.Pie(labels=top_10_labels, values=top_10_values, textinfo="percent+label")])

# グラフを表示
fig.show()

その14

from pptx import Presentation
from pptx.util import Inches
# プレゼンテーションを作成
prs = Presentation("template.pptx")  # テンプレートファイルを指定
# プレースホルダー名とJSONデータをマッピング
data = [
    {"PlaceholderName": "Title", "Text": "Title 1"},
    {"PlaceholderName": "Content", "Text": "Content 1"},
    # 他のデータ行も追加
]
# ページに収まる行数を計算
lines_per_page = 10  # 例: 1ページに10行
# スライドを追加し、プレースホルダーにデータを挿入
current_slide = None
for item in data:
    if current_slide is None:
        current_slide = prs.slides.add_slide(prs.slide_layouts[5])  # 新しいスライドを作成
    current_slide.shapes[item["PlaceholderName"]].text = item["Text"]
    if len(current_slide.shapes[item["PlaceholderName"]].text_frame.paragraphs) >= lines_per_page:
        current_slide = None  # ページが変わる場合、新しいスライドを作成
# PowerPointファイルを保存
prs.save("output.pptx")

その15

from pptx import Presentation
# プレゼンテーションを作成
prs = Presentation()
# テンプレートファイルを読み込む(.pptxファイル)
template = Presentation("your_template.pptx")
# スライドマスターの名前を指定
slide_master_name = "Your Slide Master Name"
# 指定した名前のスライドマスターを探す
selected_slide_master = None
for slide_master in template.slide_master:
    if slide_master.name == slide_master_name:
        selected_slide_master = slide_master
        break
if selected_slide_master:
    # 新しいスライドを作成し、指定したスライドマスターを適用
    slide = prs.slides.add_slide(selected_slide_master)
else:
    print(f"Slide Master '{slide_master_name}' not found in the template.")
# プレゼンテーションを保存
prs.save("output.pptx")

その16

from pptx import Presentation
from pptx.util import Pt
import json

# プレゼンテーションを作成
prs = Presentation()

# テンプレートファイルを読み込む(.pptxファイル)
template = Presentation("your_template.pptx")

# JSONデータを読み込む
with open("your_data.json", "r") as json_file:
    data = json.load(json_file)

# 1ページに表示できる最大行数
max_lines_per_page = 10

# スライドマスターを指定
slide_master = template.slide_master[0]

# ページ数を計算
total_pages = len(data) // max_lines_per_page + 1

for page_number in range(total_pages):
    # 新しいスライドを作成し、スライドマスターを適用
    slide = prs.slides.add_slide(slide_master)

    # プレースホルダー1とプレースホルダー2を取得
    placeholder1 = slide.placeholders[0]
    placeholder2 = slide.placeholders[1]

    # JSONデータから現在のページに挿入するデータを取得
    start_index = page_number * max_lines_per_page
    end_index = start_index + max_lines_per_page
    page_data = data[start_index:end_index]

    # プレースホルダー1にデータを挿入
    text_frame1 = placeholder1.text_frame
    for line in page_data:
        p = text_frame1.add_paragraph()
        p.text = line["placeholder1_data"]
        p.space_before = Pt(14)  # 適切なスペースを設定

    # プレースホルダー2にデータを挿入
    text_frame2 = placeholder2.text_frame
    for line in page_data:
        p = text_frame2.add_paragraph()
        p.text = line["placeholder2_data"]
        p.space_before = Pt(14)  # 適切なスペースを設定

# プレゼンテーションを保存
prs.save("output.pptx")

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS