I.グラフの文字化け

Pythonのグラフを作成した場合、日本語は文字が四角になります。

フォントを指定して日本語を表示する方法を紹介します。ただし、長音の記号を表示する方法は今のところ不明です。

実際のデータでグラフを作成します。

データは、Moodleのアンケート結果です。

# ライブラリをインポート
import pandas as pd
import janitor
import matplotlib.pyplot as plt
# データを読み込む
df = pd.read_csv('data/2021w1qnn_copy.csv')
# 列名を表示
print(df.columns)
## Index(['Surname', 'First name', 'ID number', 'State', 'Started on',
##        'Completed', 'Time taken', 'Grade/10.00', 'Question 1', 'Response 1',
##        'Question 2', 'Response 2', 'Question 3', 'Response 3', 'Question 4',
##        'Response 4', 'Question 5', 'Response 5', 'Question 6', 'Response 6',
##        'Question 7', 'Response 7', 'Question 8', 'Response 8'],
##       dtype='object')

列名をクリーンにします。

# 列名をクリーンに
df_cleaned = janitor.clean_names(df)
# 列名を表示
print(df_cleaned.columns)
## Index(['surname', 'first_name', 'id_number', 'state', 'started_on',
##        'completed', 'time_taken', 'grade_10_00', 'question_1', 'response_1',
##        'question_2', 'response_2', 'question_3', 'response_3', 'question_4',
##        'response_4', 'question_5', 'response_5', 'question_6', 'response_6',
##        'question_7', 'response_7', 'question_8', 'response_8'],
##       dtype='object')

各回答の選択肢の頻度の一覧を取得します。


df1 = df_cleaned.iloc[:, [9, 11, 13, 15, 17, 19, 21]]
# show frequencies
mylist = ['response_1', 'response_2', 'response_3', 'response_4', 'response_5', 'response_6', 'response_7']
for ls in mylist:
  results = df1[ls].value_counts()
  print(results)
## スマートフォン(iPhone)    14
## コンピュータ(Windows)     4
## コンピュータ(Mac)         2
## タブレット(iPad)         1
## Name: response_1, dtype: int64
## どちらかというとそう思う      9
## どちらともいえない         6
## どちらかというとそう思わない    3
## そう思う              3
## Name: response_2, dtype: int64
## どちらかというとそう思う    13
## そう思う             5
## どちらともいえない        3
## Name: response_3, dtype: int64
## 使ったことがない。                                      14
## 足し算(たしざん)や掛け算(かけざん)など簡単な計算ができる。                 4
## sum関数を使える。                                      1
## 使ったことがない。; 足し算(たしざん)や掛け算(かけざん)など簡単な計算ができる。      1
## 足し算(たしざん)や掛け算(かけざん)など簡単な計算ができる。; sum関数を使える。     1
## Name: response_4, dtype: int64
## どちらかというとそう思う      11
## どちらともいえない          4
## どちらかというとそう思わない     3
## そう思う               3
## Name: response_5, dtype: int64
## どちらかというとそう思う      8
## どちらかというとそう思わない    4
## どちらともいえない         4
## そう思う              4
## そう思わない            1
## Name: response_6, dtype: int64
## どちらかというとそう思う      9
## そう思う              6
## どちらともいえない         4
## どちらかというとそう思わない    1
## そう思わない            1
## Name: response_7, dtype: int64

回答1の選択肢それぞれの頻度のバー・チャートを作成します。

フォントを指定しない場合、次のように文字が抜けました。

日本語が含まれているフォント’Hiragino Maru Gothic Pro’を指定しました。

plt.rcParams['font.family'] = 'Hiragino Maru Gothic Pro'
# create a bar chart
df1['response_1'].value_counts().plot(kind='bar') 
plt.xticks(rotation=10)
## (array([0, 1, 2, 3]), [Text(0, 0, 'スマートフォン(iPhone)'), Text(1, 0, 'コンピュータ(Windows)'), Text(2, 0, 'コンピュータ(Mac)'), Text(3, 0, 'タブレット(iPad)')])
plt.ylabel("number",  fontsize=18)
plt.title("遠隔授業の場合に何を使いますか?")
plt.show()  

使用できるフォントの一覧を表示するスクリプトは次です。適切なものがない場合は新たにインストールします。

import matplotlib
fonts = set([f.name for f in matplotlib.font_manager.fontManager.ttflist])
print(fonts)
## {'Noto Sans Glagolitic', 'Khmer Sangam MN', 'Myanmar Sangam MN', 'Chalkduster', 'Athelas', 'Noto Sans Cypriot', 'Geeza Pro', 'Noto Sans Phoenician', 'Noto Sans Old Italic', 'Skia', 'New Peninim MT', 'STIXIntegralsUpSm', 'Tamil MN', 'System Font', 'Noto Sans Tai Le', 'Noto Sans Brahmi', 'Sinhala Sangam MN', 'Baskerville', 'Copperplate', 'xkcd', 'Kannada MN', 'Baghdad', 'cmmi10', 'Noto Sans Carian', 'Sana', 'cmex10', 'Thonburi', 'Noto Sans Gothic', 'Savoye LET', 'Tahoma', 'Gurmukhi MT', 'AppleGothic', 'Gurmukhi Sangam MN', 'PT Mono', 'ITF Devanagari', 'Muna', 'Devanagari MT', 'Noto Sans Tai Viet', 'Kokonor', 'Apple Chancery', 'Wingdings 3', 'Phosphate', 'Charter', 'Microsoft Sans Serif', 'STIXNonUnicode', 'Herculanum', 'Ayuthaya', 'Noto Sans Tai Tham', 'Apple Braille', 'Avenir Next', 'Arial Rounded MT Bold', 'Noto Sans Javanese', 'Arial', 'Noto Sans Old Turkic', 'Kohinoor Devanagari', 'Malayalam MN', 'Bodoni 72 Smallcaps', 'STIXSizeTwoSym', 'Euphemia UCAS', 'Helvetica', 'Times', 'Seravek', 'HolidayMDJP05', 'Hiragino Maru Gothic Pro', 'Webdings', 'PingFang HK', 'SetoFont', '.SF Compact Text', 'Bangla Sangam MN', 'Menlo', 'Impact', 'Avenir Next Condensed', 'Noto Sans Lepcha', 'Lucida Grande', 'PT Sans', 'Mshtakan', 'Chalkboard SE', 'Courier New', 'Optima', 'DIN Alternate', 'Cochin', 'Shree Devanagari 714', 'STIXIntegralsUp', 'Wingdings', 'Noto Sans Bamum', 'Kailasa', 'Galvji', 'Noto Sans Yi', 'Noto Sans Tagbanwa', 'Noto Sans Batak', 'Hiragino Mincho ProN', 'Diwan Kufi', 'Zapfino', 'DIN Condensed', 'DejaVu Serif Display', '.Aqua Kana', 'Big Caslon', 'DejaVu Sans Display', 'Noteworthy', 'Kohinoor Telugu', 'Noto Sans Lycian', 'Al Tarikh', 'Devanagari Sangam MN', 'Noto Sans Lydian', 'Raanana', 'Farah', 'Krungthep', 'Didot', 'Mukta Mahee', 'Kannada Sangam MN', 'Noto Sans Syloti Nagri', 'Damascus', 'Songti SC', 'STIXGeneral', '.New York', 'Noto Sans Osmanya', 'PT Serif Caption', 'Superclarendon', 'Noto Sans Cham', 'Heiti TC', 'STIXSizeThreeSym', 'Farisi', 'Marker Felt', 'Noto Sans Old South Arabian', 'Noto Sans Lisu', 'KufiStandardGK', 'Noto Sans Limbu', 'Arial Black', 'Noto Sans Chakma', 'Futura', 'Noto Sans Kharoshthi', 'Hiragino Sans', 'Telugu MN', 'cmr10', '.SF NS Display Condensed', 'Palatino', 'Bradley Hand', 'Silom', 'Noto Sans Ol Chiki', 'cmsy10', 'Snell Roundhand', 'Noto Sans Kaithi', 'Avenir', 'Trebuchet MS', 'Noto Sans Syriac', 'Al Bayan', 'Hoefler Text', 'Noto Sans Tifinagh', 'Comic Sans MS', 'Noto Sans Cuneiform', 'Bodoni 72', 'Symbol', 'STIXSizeFiveSym', 'Times New Roman', 'Noto Sans Armenian', 'Noto Sans Mongolian', 'STIXSizeFourSym', 'FontAwesome', 'Gill Sans', 'Oriya Sangam MN', 'Kefa', 'DecoType Naskh', 'Verdana', 'Khmer MN', 'Rockwell', 'Gujarati Sangam MN', 'Noto Sans Coptic', 'Arial Narrow', 'Noto Sans Egyptian Hieroglyphs', 'Noto Serif Balinese', 'Noto Sans Tagalog', 'Diwan Thuluth', 'Sukhumvit Set', 'cmtt10', 'SignPainter', 'Noto Sans Buginese', '.Arabic UI Display', 'Nadeem', 'Arial Unicode MS', '.Keyboard', 'Myanmar MN', 'Noto Sans Oriya', 'cmss10', 'Marion', 'Sinhala MN', 'Noto Sans PhagsPa', 'Noto Sans Mandaic', 'Noto Sans Vai', 'Sathu', 'Noto Nastaliq Urdu', 'Noto Sans Rejang', 'Noto Sans Buhid', 'Brush Script MT', '.SF NS Text Condensed', 'DejaVu Sans Mono', 'Kohinoor Bangla', 'American Typewriter', '.SF Compact Display', 'Bodoni 72 Oldstyle', 'Noto Sans Shavian', 'Noto Sans Saurashtra', 'Beirut', 'Malayalam Sangam MN', 'Apple SD Gothic Neo', 'STIXVariants', 'Gujarati MT', 'Noto Sans Ogham', 'Mishafi Gold', 'Noto Sans Kannada', 'Lao Sangam MN', 'Trattatello', 'Noto Sans Linear B', 'Lao MN', 'AppleMyungjo', 'Noto Sans Ugaritic', 'Arial Hebrew', 'Hiragino Sans GB', '.Arabic UI Text', 'Telugu Sangam MN', 'Bangla MN', 'DejaVu Sans', 'cmb10', '.SF NS Rounded', 'Noto Sans New Tai Lue', 'Chalkboard', 'Wingdings 2', 'InaiMathi', 'Noto Sans Avestan', 'Noto Sans Inscriptional Pahlavi', 'Al Nile', 'Georgia', 'STIXSizeOneSym', 'Noto Sans Sundanese', 'Gurmukhi MN', 'Noto Sans Hanunoo', 'Iowan Old Style', 'Noto Sans Imperial Aramaic', 'Noto Serif Myanmar', 'Noto Sans Samaritan', 'Oriya MN', 'Kohinoor Gujarati', 'Bodoni Ornaments', 'Luminari', '.SF Compact Rounded', 'Noto Sans Thaana', '.Helvetica Neue DeskInterface', 'Andale Mono', 'PT Serif', 'Noto Sans Runic', 'STIXIntegralsUpD', 'Plantagenet Cherokee', 'STIXIntegralsD', 'Noto Sans Kayah Li', 'Zapf Dingbats', 'STIXIntegralsSm', 'Apple Symbols', 'Noto Sans Meetei Mayek', 'Papyrus', 'Tamil Sangam MN', 'Noto Sans Old Persian', 'Waseem', '.SF NS Mono', 'DejaVu Serif', 'Corsiva Hebrew', 'Noto Sans Myanmar', 'MesloLGS NF', 'Mishafi', 'Noto Sans NKo', 'SetoFont-ex', 'Noto Sans Inscriptional Parthian', 'Helvetica Neue'}