[英]Plot by Categorical Group in Python Plotly
我有一個只有 5 個變量的 Pandas 數據框。 我想通過分類變量創建散點圖和顏色。 我正在使用 plotly,所以我可以放大到特定區域。 Plotly 不允許我將分類變量列表作為顏色傳遞。 先感謝您! 這是我的代碼:
import plotly.graph_objs as go
import plotly.plotly as py
import plotly.tools
plotly.tools.set_credentials_file(username='user', api_key='key')
trace1 = go.Scatter(
x = df['var1'],
y = df['var2'],
mode='markers',
marker=dict(
size=16,
color = df['categorialVar'], #set color equal to a variable
showscale=True
)
)
data = [trace1]
py.iplot(data, filename='scatter-plot-with-colorscale')
最近遇到了這個問題並提出了解決方案:
def get_random_qualitative_color_map(
categorial_series: pd.Series,
colors: typing.List[str] = plotly_colors.qualitative.Alphabet
) -> typing.List[str]:
"""
Returns a color coding for a given series (one color for every unique value). Will repeat colors if not enough are
provided.
:param categorial_series: A series of categorial data
:param colors: color codes (everything plotly accepts)
:return: Array of colors matching the index of the objects
"""
# get unique identifiers
unique_series = categorial_series.unique()
# create lookup table - colors will be repeated if not enough
color_lookup_table = dict((value, color) for (value, color) in zip(unique_series, itertools.cycle(colors)))
# look up the colors in the table
return [color_lookup_table[key] for key in categorial_series]
unique_series = categorial_series.unique()
首先,我們獲得系列中的唯一值。 他們每個人都會匹配一種顏色。
color_lookup_table = dict((value, color) for (value, color) in zip(unique_series, itertools.cycle(colors)))
接下來我們將創建一個 dict(用作查找表 - 我們可以查找哪種顏色屬於哪個類別元素。這里棘手的部分是使用itertools.cycle(colors)
。該函數將返回一個始終循環的迭代器給定迭代中的所有值(在這種情況下是由 plot.ly 定義的顏色列表)。
接下來我們將zip
這個迭代器和實際的唯一項。 這將創建成對 (unique_item, color)。 我們得到了永遠不會用完顏色的好效果(因為循環迭代器將無休止地運行)。 這意味着返回的 dict 將有len(unique_series)
項。
[color_lookup_table[key] for key in categorial_series]
最后,我們使用列表推導在查找表中查找系列中的每個條目。 這將創建數據點的顏色列表。 然后,該列表可以用作任何plotly.graphics_object
標記字典中的color
參數的參數。
因此,我沒有繼續尋找 plotly 的解決方案,而是繼續使用 seaborn 可視化庫,並添加了“%matplotlib notebook”,它工作得很好而且很容易。
%matplotlib notebook
# Plot t-SNE
sns.set_context("notebook", font_scale=1.1)
sns.set_style("ticks")
sns.lmplot(x='var1',
y='var2',
data=tsne_out,
fit_reg=False,
legend=True,
size=9,
hue='categorialVar',
scatter_kws={"s":200, "alpha":0.3})
plt.title('Plot Title', weight='bold').set_fontsize('14')
plt.xlabel('Dimension 1', weight='bold').set_fontsize('10')
plt.ylabel('Dimension 2', weight='bold').set_fontsize('10')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.