gpt4 book ai didi

python - savefig 未保存树状图轴

转载 作者:行者123 更新时间:2023-12-01 02:48:40 27 4
gpt4 key购买 nike

我正在尝试保存由大表(10000+行,18列)制成的大树状图,我附带了这段代码

from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy as np
import pandas as pd

data = pd.read_csv("Input.txt", header = 0, index_col = None,\
sep = "\t", memory_map = True)
data = data.fillna(0)
Matrix = data.iloc[:,-18:]

Linkage_Matrix = linkage (Matrix, "ward")
fig=plt.figure(figsize=(20, 200))
#fig, ax = plt.subplots(1, 1, tight_layout=False)
ax = fig.add_axes([0.1,0.1,0.75,0.75])
#fig.title('Hierarchical Clustering Dendrogram')
ax.set_title("Hierarchical Clustering Dendrogram")
ax.set_xlabel("distance")
ax.set_xlabel("name")
dendrogram(
Linkage_Matrix,
orientation ="left",
leaf_rotation=0.,
leaf_font_size=12.,
labels = list(data.loc[:,"name"])
)
ax.set_yticklabels(list(data.loc[:,"name"]), minor=False)
ax.yaxis.set_label_position('right')
ax.yaxis.tick_right()

plt.savefig("plt1.png", dpi = 320, format= "png", bbox_inches=None)

但不幸的是,它没有保存轴,而我留下了一些空间,如下所示:
Matplotlib savefig does not save axes
Why is my xlabel cut off in my matplotlib plot?
Matplotlib savefig image trim Plotting hierarchical clustering dendrograms for large data sets Dendrogram generated by scipy-cluster customisation我在控制台中有正确的显示,我可以保存它,但 dpi 不好,理想情况下我还想切换到 svg 以便之后能够设置可读性级别。

任何见解将不胜感激

最佳答案

删除此行

ax = fig.add_axes([0.1,0.1,0.75,0.75])

并在plt.savefig()中设置bbox_inches='tight'使其对我有用。

此外,由于您使用 pandas 加载数据,请注意如何将“name”列声明为索引并使用这些索引值作为标签。

from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy as np
import pandas as pd


data = pd.read_csv('input.txt', header=0, index_col=['name'], sep="\t")
data = data.fillna(0)

link_matrix = linkage(data, 'ward')
fig, ax = plt.subplots(1, 1, figsize=(20,200))
ax.set_title('Hierarchical Clustering Dendrogram')
ax.set_xlabel('distance')
ax.set_ylabel('name')
dendrogram(
link_matrix,
orientation='left',
leaf_rotation=0.,
leaf_font_size=12.,
labels=data.index.values
)
ax.yaxis.set_label_position('right')
ax.yaxis.tick_right()
plt.savefig('plt1.png', dpi=320, format='png', bbox_inches='tight')

关于python - savefig 未保存树状图轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45033052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com