提问人:Leo 提问时间:5/21/2019 最后编辑:jakevdpLeo 更新时间:5/21/2019 访问量:351
Altair mark_line 比 matplotlib 更嘈杂的情节?
Altair mark_line plots noisier than matplotlib?
问:
我正在学习 altair 为我的情节添加交互性。我正在尝试重新创建我在 matplotlib 中所做的绘图,但是 altair 正在为我的曲线添加噪音。
这是我的数据集 DF1
从 GitHub 链接到这里: https://raw.githubusercontent.com/leoUninova/Transistor-altair-plots/master/df1.csv
代码如下:
fig, ax = plt.subplots(figsize=(8, 6))
for key, grp in df1.groupby(['Name']):
y=grp.logabsID
x=grp.VG
ax.plot(x, y, label=key)
plt.legend(loc='best')
plt.show()
#doing it directly from link
df1='https://raw.githubusercontent.com/leoUninova/Transistor-altair-plots/master/df1.csv'
import altair as alt
alt.Chart(df1).mark_line(size=1).encode(
x='VG:Q',
y='logabsID:Q',
color='Name:N'
)
这是我正在生成的绘图的图像:matplotlib 与 altair 绘图
如何消除 altair 的噪音?
答:
3赞
jakevdp
5/21/2019
#1
Altair 在绘制线条之前对 x 轴进行排序,因此,如果一组中有多条线,则通常会导致“噪声”,正如您所说的那样。这不是噪声,而是数据集中所有点的准确表示,以默认排序顺序显示。下面是一个简单的示例:
import numpy as np
import pandas as pd
import altair as alt
df = pd.DataFrame({
'x': [1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
'y': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'group': [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
})
alt.Chart(df).mark_line().encode(
x='x:Q',
y='y:Q'
)
解决此问题的最佳方法是将编码设置为一列,以区分要单独绘制的不同行:detail
alt.Chart(df).mark_line().encode(
x='x:Q',
y='y:Q',
detail='group:N'
)
如果重要的不是分组,而是点的顺序,则可以通过提供顺序通道来指定分组:
alt.Chart(df.reset_index()).mark_line().encode(
x='x:Q',
y='y:Q',
order='index:Q'
)
请注意,这两条线在右端连接。这实际上是 matplotlib 默认执行的操作:即使有重复的数据,它也会保持索引顺序。使用数据的订单渠道可生成您正在寻找的结果:
df1 = pd.read_csv('https://raw.githubusercontent.com/leoUninova/Transistor-altair-plots/master/df1.csv')
alt.Chart(df1.reset_index()).mark_line(size=1).encode(
x='VG:Q',
y='logabsID:Q',
color='Name:N',
order='index:Q'
)
每组中的多条线按末端连接的顺序绘制,就像在 matplotlib 中一样。
评论