
[英]Matplotlib: Create a continous colorbar from concrete values and corresponding colors
[英]Matplotlib create text with colors corresponding to series
我正在嘗試為不同系列創建一個具有不同顏色的情節。 當我嘗試將圖中的數據添加為文本框時,出現了問題。
我使用的代碼如下:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import scipy.stats as stats
df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500], 'y':[3000, 2100, 1500, 3000, 2500, 2000], 'z':['a', 'b', 'c', 'd', 'e', 'f']})
fig, ax = plt.subplots(figsize=(8,6))
text_list = []
color_list = []
for i, row in df.iterrows():
mu, sigma, group = row['x'], row['y'], row['z']
x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)
sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
color = ax.get_lines()[-1].get_c()
ax = plt.gca()
ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color) #only retrieve RGB so blank text is not too light
text = r'{0}: {1} $\pm$ {2}'.format(group, mu, sigma)
text_list.append(text)
color_list.append(color)
plt.gcf().text(0.68, 0.6, '\n'.join(text_list), bbox=dict(facecolor='white', edgecolor='black', pad=10.0, alpha=1), fontsize=14)
fig.show()
bbox中的文本均為黑色。 理想情況下,文本框中的每條線應具有與圖中相應系列相同的顏色。
我能夠在text_box_content和color_list中保存兩個文本和顏色列表。 我還嘗試在具有動態更新的文本位置的for循環中添加plt.gcf().text()
,但是為每行創建了邊框,而不是為所有文本創建了整體邊框。
如果在概念上有類似的東西會更好
plt.gcf().text(zip(text_list, color_list))
所以每行可以有自己的顏色嗎?
您可以創建圖例,並通過其所屬行的顏色為每個圖例項上色。 如果您不想在圖例中顯示該行本身,則可以顯示相應的字母作為圖例句柄。
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerBase
from matplotlib.text import Text
import seaborn as sns
import numpy as np
import scipy.stats as stats
class TextHandler(HandlerBase):
def create_artists(self, legend,tup ,xdescent, ydescent,
width, height, fontsize,trans):
tx = Text(width/2.,height/2,tup[0], fontsize=fontsize,
ha="center", va="center", color=tup[1], fontweight="bold")
return [tx]
df = pd.DataFrame({'x': [21000, 16900, 18200, 32000, 35000, 7500],
'y':[3000, 2100, 1500, 3000, 2500, 2000],
'z':['a', 'b', 'c', 'd', 'e', 'f']})
fig, ax = plt.subplots(figsize=(8,6))
handles = []
labels = []
for i, row in df.iterrows():
mu, sigma, group = row['x'], row['y'], row['z']
x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)
sns.lineplot(x, stats.norm.pdf(x, mu, sigma), ax=ax)
color = ax.get_lines()[-1].get_c()
ax.text(mu*1.05, max(stats.norm.pdf(x, mu, sigma)), group, fontsize=16, color=color)
handles.append(("{}:".format(group), color))
labels.append("{} $\pm$ {}".format(mu, sigma))
leg = ax.legend(handles=handles, labels=labels, handler_map={tuple : TextHandler()},
facecolor='white', edgecolor='black', borderpad=0.9, framealpha=1,
fontsize=10, handlelength=0.5)
for h, t in zip(leg.legendHandles, leg.get_texts()):
t.set_color(h.get_color())
plt.show()
這是受到我對這個問題的回答的啟發並部分使用了代碼,在您不想使用圖例的情況下,它也提供了另一種選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.