python 绘制树形图时浮点数除以零
python float division by zero when plotting treemap chart
我是 python matplotlib 的新手,正在尝试绘制树形图,在此先感谢!
squarify.plot(sizes=df['vvmins'], label=df['category_name'], alpha=.8)
plt.axis('off')
plt.show()
然后出现 'float division by zero' 错误,我的数据集如下(虚拟):
我运行陷入同样的问题。这些选项中的任何一个都应该有效:
- 如评论中所述,提前删除任何 0 值。对于 Pandas 数据框,这可以通过在绘图之前过滤不具有 0 值的行来实现。 (目前在下面的代码中被注释掉了)。或者,
- 如果您想保留值为 0 的标签,您可以在所有尺码中添加一个非常小的分数。
import pandas as pd
import matplotlib
import squarify
df = pd.DataFrame(
{"category_name": ["a", "c", "k", "s", "e", "d", "a", "d", "e", "s", "z", "k", "k", "k"],
"vvmins": [4, 9, 2, 4, 5, 5, 9, 6, 3, 5, 7, 5, 2, 0],
}
)
##### OPTION 1 #####
# Filter out rows with value of 0
# df = df.loc[df["vvmins"] != 0]
##### OPTION 2 #####
# Add a very small number to each element of size column
df["vvmins"] = df["vvmins"].apply(lambda x: x + 0.000001)
# Optional sorting of categories so like labels are together
# Pairs well with OPTION 1
# df.sort_values("category_name", inplace=True)
# Plot as before
squarify.plot(sizes=df["vvmins"],
label=df["category_name"],
alpha=0.8,
pad=True # adds white space; 0-value label more visible
)
plt.axis("off")
plt.show()
我是 python matplotlib 的新手,正在尝试绘制树形图,在此先感谢!
squarify.plot(sizes=df['vvmins'], label=df['category_name'], alpha=.8)
plt.axis('off')
plt.show()
然后出现 'float division by zero' 错误,我的数据集如下(虚拟):
我运行陷入同样的问题。这些选项中的任何一个都应该有效:
- 如评论中所述,提前删除任何 0 值。对于 Pandas 数据框,这可以通过在绘图之前过滤不具有 0 值的行来实现。 (目前在下面的代码中被注释掉了)。或者,
- 如果您想保留值为 0 的标签,您可以在所有尺码中添加一个非常小的分数。
import pandas as pd
import matplotlib
import squarify
df = pd.DataFrame(
{"category_name": ["a", "c", "k", "s", "e", "d", "a", "d", "e", "s", "z", "k", "k", "k"],
"vvmins": [4, 9, 2, 4, 5, 5, 9, 6, 3, 5, 7, 5, 2, 0],
}
)
##### OPTION 1 #####
# Filter out rows with value of 0
# df = df.loc[df["vvmins"] != 0]
##### OPTION 2 #####
# Add a very small number to each element of size column
df["vvmins"] = df["vvmins"].apply(lambda x: x + 0.000001)
# Optional sorting of categories so like labels are together
# Pairs well with OPTION 1
# df.sort_values("category_name", inplace=True)
# Plot as before
squarify.plot(sizes=df["vvmins"],
label=df["category_name"],
alpha=0.8,
pad=True # adds white space; 0-value label more visible
)
plt.axis("off")
plt.show()