質問編集履歴

1

試したことを追加

2023/06/15 12:11

投稿

Muuuuki
Muuuuki

スコア26

test CHANGED
File without changes
test CHANGED
@@ -1,6 +1,9 @@
1
1
  ### 実現したいこと
2
2
 
3
- 現在,様々なサイトを参考に,1つの要素(教科)を縦軸積み上げ棒グラフで図示することはできているのですが(ただ凡例は表示されず),これを指定した要素全てで横軸積み上げ棒グラフにまとめたいです。
3
+ 現在,様々なサイトを参考に,1つの要素(教科)を積み上げ棒グラフで図示することはできているのですが(ただ凡例は表示されず),これを指定した要素全てで横軸積み上げ棒グラフにまとめたいです。
4
+
5
+ ### 修正点
6
+ ご指摘をいただき,横軸積み上げ棒グラフにして,2つまでの要素を図示できました。英語を同様に追加するとエラーが出てしまうため,3つ以上で図示する方法をご教示いただきますと嬉しい限りです。
4
7
 
5
8
  ### データの詳細
6
9
  使用するデータは,下記のような授業アンケートで,各教科に対して「満足」「やや満足」「どちらとも言えない」「やや不満」「不満」という回答が格納されております。
@@ -19,15 +22,55 @@
19
22
  import matplotlib.pyplot as plt
20
23
  import japanize_matplotlib
21
24
 
25
+ # カテゴリの順番を定義
26
+ category_order = ["満足","やや満足","どちらとも言えない","やや不満","不満"]
27
+
28
+ # カテゴリの順番に基づいてデータをソート
22
- tmp=df[" [国語]"].value_counts(normalize=True).sort_index().reset_index()
29
+ tmp = df[["国語", "数学", "英語", "社会", "理科"]].apply(lambda x: x.value_counts(normalize=True)).reindex(category_order).reset_index()
30
+
31
+ width = 0.4 # 棒の幅
32
+ y = [1, 2] # y軸の位置
33
+
23
- bottom = 0
34
+ left1 = 0
35
+ left2 = 0
36
+ colors = ["skyblue", "steelblue", "deepskyblue", "royalblue", "lightsteelblue"] # 各カテゴリに対する色のリスト
37
+
24
38
  for i in range(tmp.shape[0]):
25
- plt.bar(1, tmp["国語"][i],bottom=bottom)
39
+ plt.barh(y[0], tmp["国語"][i], left=left1, height=width, label="国語", color=colors[i % len(colors)])
40
+ plt.barh(y[1], tmp["数学"][i], left=left2, height=width, label="数学", color=colors[i % len(colors)])
26
- bottom += tmp["国語"][i]
41
+ left1 += tmp["国語"][i]
42
+ left2 += tmp["数学"][i]
43
+
44
+ plt.plot([0, 0], [0, 3], color='#00000000')
45
+ plt.yticks(y, ["国語", "数学"])
46
+
47
+ # 凡例を表示
27
- plt.legend()
48
+ #plt.legend()
49
+
28
- plt.plot([0,2],[0,0],color='#00000000')
50
+ plt.show()
29
51
  ```
30
- ![イメージ説明](https://ddjkaamml8q8x.cloudfront.net/questions/2023-06-15/c74e6fb2-09f9-4993-a7c1-6cfae7bb3236.png)
52
+ ![イメージ説明](https://ddjkaamml8q8x.cloudfront.net/questions/2023-06-15/10fd9aa0-c554-43f3-94cd-bea5e0dd5c83.png)
53
+
54
+ ### 試したこと
55
+ ```python
56
+ left1 = 0
57
+ left2 = 0
58
+ left3 = 0
59
+ colors = ["skyblue", "steelblue", "deepskyblue", "royalblue", "lightsteelblue"] # 各カテゴリに対する色のリスト
60
+
61
+ for i in range(tmp.shape[0]):
62
+ plt.barh(y[0], tmp["国語"][i], left=left1, height=width, label="国語", color=colors[i % len(colors)])
63
+ plt.barh(y[1], tmp["数学"][i], left=left2, height=width, label="数学", color=colors[i % len(colors)])
64
+ plt.barh(y[2], tmp["英語"][i], left2=left3, height=width, label="英語", color=colors[i % len(colors)])
65
+ left1 += tmp["国語"][i]
66
+ left2 += tmp["数学"][i]
67
+ left3 += tmp["英語"][i]
68
+
69
+ plt.plot([0, 0], [0, 3], color='#00000000')
70
+ plt.yticks(y, ["国語", "数学","英語"])
71
+ ```
72
+
73
+ IndexError: list index out of range
31
74
 
32
75
  ### 補足
33
76
  可能でしたら,下記画像のように(積み上げ棒グラフで)性別別に横軸積み上げ棒グラフを2つ並べられたらと嬉しいです…