簡體   English   中英

修改matplotlib和seaborn中的colorbar

[英]modifying colorbar in matplotlib and seaborn

我正在嘗試保存使用seaborn生成的圖像。 圖像是4x4混淆矩陣(“ confmat” np.array)。 我了解到,當我將圖像保存為矢量格式時,某些查看器會出現問題,導致顏色條上出現白線,並引用了matplotlib參考:

眾所周知,某些矢量圖形查看器(svg和pdf)會在色條的各段之間呈現白色間隙。 這是由於查看器中的錯誤而不是matplotlib。 作為解決方法,可以使用重疊的段來呈現顏色欄:

cbar = colorbar()

cbar.solids.set_edgecolor(“ face”)

畫()

但是,我在執行建議時遇到了麻煩。

這是我所做的:

import seaborn as sns
import matplotlib.pyplot as plt

cmap=plt.cm.Blues

fig, ax = plt.subplots()

ax = sns.heatmap(confmat, annot=True, cmap=cmap)
ax.set_title('title')
ax.tick_params(
    axis='both',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom='off',      # ticks along the bottom edge are off
    top='off',         # ticks along the top edge are off
    labelbottom='off',  # labels along the bottom edge are off
    labelleft='off',
    right='off')

fig.savefig('confusion_matrix.svg', format='svg')

我試圖使用

cbar = ax.colorbar()

但是出現錯誤AttributeError:'AxesSubplot'對象沒有屬性'colorbar'。

我搜索了解決方案,並在此處發現了一些問題,這些問題建議使用plt.imshow()來獲取顏色條對象,但是我對目前正在執行的操作完全感到困惑。 有人可以建議,並在可能的情況下解釋為什么,實現用於為colorbar提供哪些matplotlib文檔的解決方案嗎?

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

x = np.random.randn(10, 10)

f, ax = plt.subplots()
sns.heatmap(x)
cbar_ax = f.axes[-1]
cbar_solids = cbar_ax.collections[0]
cbar_solids.set_edgecolor("face")
f.savefig("heatmap.svg")

改變colorbarcb.solid.set_edgecolor("face")如在matplotlib文檔建議似乎是一個黑客位的,以確保有在彩條的元件之間沒有白線。 我認為seaborn的設計假設您應該能夠通過傳遞kwargs(heatmap中的cbar_kws)來完成所需的一切。 例如,您可以將cb_kwargs傳遞到sns.heatmap函數cbar_kws={"drawedges": "False"}但是不幸的是,這不能解決問題。

由於Seaborn Heatmap只返回其上的軸手柄heatplotcolorbar繪制,你不必直接訪問可映射對象, cbar在源代碼中。 因此,您無法應用此技巧。

一種解決方案是僅使用pcolormeshcolorbar進行pcolormesh 我認為seaborn實際上重新定義了matplotlib樣式,因此應該看起來一樣,

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

cmap=plt.cm.Blues

fig, ax = plt.subplots()
confmat = np.random.rand(4, 4)

cb = ax.pcolormesh(confmat, cmap=cmap)

ax.set_title('title')
ax.tick_params(
    axis='both',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom='off',      # ticks along the bottom edge are off
    top='off',         # ticks along the top edge are off
    labelbottom='off',  # labels along the bottom edge are off
    labelleft='off',
    right='off')

cbar = plt.colorbar(cb)
cbar.solids.set_edgecolor("face")
plt.draw()

fig.savefig('confusion_matrix.svg', format='svg')

當您放大時,對我來說,結果似乎擺脫了白線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM