Search code examples
pythonvisualizationaltair

Is there a way to apply this function onto an Altair scatter plot?


I am hoping I can apply this draw_vector function onto an Altair scatter plot rather than matplotlib. I am having trouble with a workaround. Your expertise would be appreciated!

def draw_vector(v0, v1, ax=None):
    ax = ax or plt.gca()
    arrowprops=dict(arrowstyle='->',
                    linewidth=2,
                    shrinkA=0, shrinkB=0)
    ax.annotate('', v1, v0, arrowprops=arrowprops)

# plot data
plt.scatter(X[:, 0], X[:, 1], alpha=0.2)
for length, vector in zip(pca.explained_variance_, pca.components_):
    v = vector * 3 * np.sqrt(length)
    draw_vector(pca.mean_, pca.mean_ + v)
plt.axis('equal');

Here is what the above code produces for reference:

enter image description here


Solution

  • I recognize that chart 😀

    Unfortunately, there is not really any support for arrows in Vega-Lite, the rendering library that Altair is built on, and so there is not really any great solution for rendering arrows with Altair. You can see a few workarounds in the tracking issue for this feature: https://github.com/altair-viz/altair/issues/914