如何使用 Pygal 旋轉 X 軸標籤?
Pygal 是一個 Python 庫,用於建立互動式、可自定義的圖表和圖形。我們可以使用 Pygal 模組中的 **x_label_rotation** 屬性來旋轉 x 軸標籤。旋轉 x 軸標籤使圖表更易於閱讀和理解。在本文中,我們將討論如何使用 Pygal 及其示例來旋轉 x 標籤。
演算法
下面給出了使用 pygal 旋轉 x 標籤的一般演算法:
匯入 Pygal 模組。
建立一個圖表物件(例如,Bar、Line、Pie 等)。
使用 add 方法將資料新增到圖表中。
使用 x_labels 屬性設定 x 軸標籤。
使用 x_label_rotation 屬性設定 x 軸標籤的旋轉角度。
使用 render_to_file 或 render_to_png 方法渲染圖表。
語法
chart.x_label_rotation = rotation_angle
這裡,chart 是 Pygal 圖表物件,rotation_angle 是要旋轉 x 軸標籤的角度(以度為單位)。
步驟 1:安裝 Pygal
第一步是安裝所需的模組。我們需要安裝 Pygal 模組才能使用它建立圖表。要安裝 Pygal 模組,只需在您的終端或命令提示符中鍵入以下命令。
pip install pygal
步驟 2:使用 Pygal 建立帶有普通 x 標籤的圖表
在此步驟中,我們需要匯入 Pygal 模組並開始建立圖表。我們將建立一個條形圖,顯示 2015 年至 2018 年不同年份的值。要繪製圖表,我們需要向 Pygal 條形圖新增值和標籤。**render_to_file()** 函式將建立的圖表渲染到名為 **`pets.svg`** 的 SVG 檔案中。繪製圖表的程式如下所示:
import pygal from pygal.style import Style style_config = { "colors": ("#0099d6", "#0099d6", "#6d6f71", "#6d6f71"), } # Create a bar chart bar_chart = pygal.Bar(style=Style(**style_config)) # Set x-axis labels bar_chart.x_labels = ['2015', '2016', '2017', '2018'] # Add data to the chart bar_chart.add('Values', [2,1,3,2]) # Render the chart bar_chart.render_to_file('pets.svg')
輸出
步驟 3:旋轉 X 標籤
預設情況下,pygal 模組會水平顯示 x 標籤。要旋轉 x 標籤,我們使用 **x_label_rotation** 屬性。此屬性採用一個整數值,該值返回以度為單位的旋轉角度。例如,如果我們給 x_label_rotation 值 90,它將順時針旋轉標籤 90 度。
要將 x_label 旋轉 45 度,我們可以將行 **bar_chart.x_label_roation=45** 新增到上面的程式碼中。旋轉後的 x 標籤的完整程式碼如下所示。輸出清楚地顯示了 x 標籤旋轉了 45 度。
import pygal from pygal.style import Style style_config = { "colors": ("#0099d6", "#0099d6", "#6d6f71", "#6d6f71"), } # Create a bar chart bar_chart = pygal.Bar(style=Style(**style_config)) # Set x-axis labels bar_chart.x_labels = ['2015', '2016', '2017', '2018'] # Add data to the chart bar_chart.add('Values', [2,1,3,2]) # Rotate the x-axis labels bar_chart.x_label_rotation = 45 # Render the chart bar_chart.render_to_file('pets_rotated.svg')
輸出
結論
在本文中,我們討論瞭如何在 Python 中使用 pygal 模組和 x_label_rotate 屬性來旋轉 x 標籤。旋轉 x_label 可以提高標籤的可讀性,使圖表更有效。我們可以根據需要提供不同的旋轉角度來旋轉 x 標籤。