我可以創建一個餅圖,其中每個楔形的大小列印如下:
df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
'radius': [2439.7, 6051.8, 6378.1]},
index=['Mercury', 'Venus', 'Earth'])
plot = df.plot.pie(y='mass', figsize=(5, 5), autopct= '%.2f')
我怎樣才能讓它只列印一個子集的值(比如不列印 Mercury)?
uj5u.com熱心網友回復:
- 使用
lambda函式有條件地放置值autopct。根據
uj5u.com熱心網友回復:
一種選擇是在創建繪圖后洗掉文本(或將其設定為不可見)。現在的主要問題是找到要修改的正確文本。例如:
import pandas as pd df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97], 'radius': [2439.7, 6051.8, 6378.1]}, index=['Mercury', 'Venus', 'Earth']) plot = df.plot.pie(y='mass', figsize=(5, 5), autopct= '%.2f') print(plot.texts)會屈服
[Text(1.09526552098778, 0.10194821496900702, 'Mercury'), Text(0.5974175569024254, 0.05560811725582201, '2.95'), Text(0.01701519685165565, 1.0998683935253797, 'Venus'), Text(0.009281016464539445, 0.5999282146502071, '43.60'), Text(-0.11887821664562105, -1.0935574834489301, 'Earth'), Text(-0.0648426636248842, -0.5964859000630527, '53.45')]所以你可以看到,這是
Text我們要關閉的第二項。一個簡單的方法是:plot.texts[1].set_visible(False)或者
plot.texts[1].remove()顯然,概括這一點的問題是提前知道要洗掉哪些文本。正如您在上面看到的,文本添加到軸的順序是索引名稱(行星名稱),然后是該行星的 autopct 標簽,然后對下一個行星重復。因此,如果您知道要洗掉行星的 autopct 標簽
i,則可以使用類似plot.texts[2 * i 1].remove().為給定的行星標簽執行此操作的輔助函式如下所示:
def remove_text(label): ind = df.index.get_loc(label) * 2 1 plot.texts[ind].remove() remove_text('Mercury')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/352680.html標籤:Python 熊猫 matplotlib 饼形图
下一篇:如何將值更改為矩陣?
