简体   繁体   English

在 altair 中设置单个点标记的大小

[英]Set size of individual point markers in altair

I've been trying to figure out how to set individual point sizes in Altair, but can't quite crack it.我一直试图弄清楚如何在 Altair 中设置单个点的大小,但不能完全破解它。 It's easy to do in matplotlib, but I'm trying to teach myself all the Altair things, and am stumped.在 matplotlib 中很容易做到,但我正在尝试自学所有 Altair 的东西,但我很难过。 Here's how I'd do it in matplotlib and my best attempt in altair:以下是我在 matplotlib 中的做法以及我在 altair 中的最佳尝试:

import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
import altair as alt

def generate_data(x, y):
  data = pd.DataFrame(
      columns = ['x', 'y', 'point_size'],
      data = {
          'x': pd.Series(np.tile(range(1,x+1), y) ),
          'y': np.repeat(range(1,x+1),y),
          'point_size': [random.randint(0,3) for i in range(0, x*y)],
          },
      )
  return data

def plot_points(data):
  fig = data.plot(
      kind='scatter',
      x='x', 
      y='y', 
      marker='.', 
      s = data['point_size']*50, # setting the size factor
      )


def plot_points_altair(data):
  fig = alt.Chart(data[data.point_size>0]).mark_point(filled=True).encode(
      x=alt.X('x'),
      y=alt.Y('y'),
      size=alt.StrokeWidth('point_size:N'),
      )
  return fig

data = generate_data(10,10)
plot_points(data)
plot_points_altair(data)

I filter out the zero values to avoid plotting them, but Altair treats my point sizes like a categorical, and I'd like control the actual point size of each point in, well, points (or pixels or picas or what have you).我过滤掉零值以避免绘制它们,但 Altair 将我的点大小视为分类,我想控制每个点的实际点大小,嗯,点(或像素或 picas 或你有什么)。

matplotlib

牵牛星

You can do this by using a size encoding with scale=None : this will tell Altair to use the raw data to control the values of the specified encoding, rather than implicitly generating a mapping between the data domain and the visual domain:您可以通过使用scale=Nonesize编码来做到这一点:这将告诉 Altair 使用原始数据来控制指定编码的值,而不是隐式生成数据域和可视域之间的映射:

import numpy as np
import pandas as pd
import random
import altair as alt

def generate_data(x, y):
  data = pd.DataFrame(
      columns = ['x', 'y', 'point_size'],
      data = {
          'x': pd.Series(np.tile(range(1,x+1), y) ),
          'y': np.repeat(range(1,x+1),y),
          'point_size': [50 * random.randint(0,3) for i in range(0, x*y)],
          },
      )
  return data


def plot_points_altair(data):
  fig = alt.Chart(data[data.point_size>0]).mark_point(filled=True).encode(
      x=alt.X('x'),
      y=alt.Y('y'),
      size=alt.Size('point_size:N', scale=None),
      )
  return fig

data = generate_data(10,10)
plot_points_altair(data)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM