## Create the bar chart
plt.bar(categories, values)
## Add title and labels
plt.title('Monthly Sales Data')
plt.xlabel('Month')
plt.ylabel('Sales ($)')
## Save the plot to a file
plt.savefig('/home/labex/project/vertical_bar_chart.png')
print("Vertical bar chart saved as vertical_bar_chart.png")
新しいコードの説明は以下の通りです。
plt.bar(categories, values): これは棒グラフを作成する中心的な関数です。categories リストを x 軸に、values リストを y 軸の棒の高さにマッピングします。
plt.title(), plt.xlabel(), plt.ylabel(): これらの関数は、それぞれグラフにタイトルを付け、x 軸と y 軸にラベルを追加し、グラフを理解しやすくします。
## Create the horizontal bar chart
plt.barh(categories, values)
## Add title and labels
plt.title('Monthly Sales Data')
plt.xlabel('Sales ($)')
plt.ylabel('Month')
## Save the plot to a file
plt.savefig('/home/labex/project/horizontal_bar_chart.png')
print("Horizontal bar chart saved as horizontal_bar_chart.png")
これで、main.py 全体は以下のようになります。
import matplotlib.pyplot as plt
## Data for the bar chart
categories = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
values = [320, 450, 500, 480, 600]
## Create the horizontal bar chart
plt.barh(categories, values)
## Add title and labels
plt.title('Monthly Sales Data')
plt.xlabel('Sales ($)')
plt.ylabel('Month')
## Save the plot to a file
plt.savefig('/home/labex/project/horizontal_bar_chart.png')
print("Horizontal bar chart saved as horizontal_bar_chart.png")
次に、更新されたスクリプトをターミナルから実行します。
python3 main.py
以下の出力が表示されます。
Horizontal bar chart saved as horizontal_bar_chart.png
import matplotlib.pyplot as plt
## Data for the bar chart
categories = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
values = [320, 450, 500, 480, 600]
colors = ['skyblue', 'lightgreen', 'salmon', 'gold', 'orchid']
## Create the bar chart with custom colors
plt.bar(categories, values, color=colors)
## Add title and labels
plt.title('Monthly Sales Data')
plt.xlabel('Month')
plt.ylabel('Sales ($)')
## Save the plot to a file
plt.savefig('/home/labex/project/colored_bar_chart.png')
print("Colored bar chart saved as colored_bar_chart.png")
このコードでは:
グラフの各棒に対応する色のリストである colors リストを定義しました。
このリストを plt.bar(categories, values, color=colors) の color パラメータに渡しました。
import matplotlib.pyplot as plt
## Data for the bar chart
categories = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
values = [320, 450, 500, 480, 600]
## Create the bar chart with a label
plt.bar(categories, values, color='skyblue', label='This Year Sales')
## Add title and labels
plt.title('Monthly Sales Data')
plt.xlabel('Month')
plt.ylabel('Sales ($)')
## Add the legend
plt.legend()
## Save the plot to a file
plt.savefig('/home/labex/project/bar_chart_with_legend.png')
print("Bar chart with legend saved as bar_chart_with_legend.png")
変更点は以下の通りです。
plt.bar() に label='This Year Sales' パラメータを追加しました。これにより、データセットに名前が割り当てられます。