牛郎星标记线图比matplotlib更吵?

2024-04-29 06:51:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习牛郎星添加互动到我的情节。我试图重建一个情节,我在matplotlib做,但牛郎星是增加噪音,我的曲线。你知道吗

这是我的数据集 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 vs altair plot

如何消除牛郎星的噪音?你知道吗


Tags: httpsmastercomrawmatplotlibpltdf1情节
1条回答
网友
1楼 · 发布于 2024-04-29 06:51:00

牵牛星在画线之前会对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'
)

enter image description here

解决此问题的最佳方法是将detail编码设置为一列,以区分要单独绘制的不同行:

alt.Chart(df).mark_line().encode(
    x='x:Q',
    y='y:Q',
    detail='group:N'
)

enter image description here

如果重要的不是分组,而是点的顺序,则可以通过提供order channel来指定:

alt.Chart(df.reset_index()).mark_line().encode(
    x='x:Q',
    y='y:Q',
    order='index:Q'
)

enter image description here

请注意,这两条线是在右端连接的。这实际上是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'
)

enter image description here

每组中的多条线是按末端连接的顺序绘制的,与matplotlib中的一样。你知道吗

相关问题 更多 >