AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 77560983
Accepted
KansaiRobot
KansaiRobot
Asked: 2023-11-28 10:18:31 +0800 CST2023-11-28 10:18:31 +0800 CST 2023-11-28 10:18:31 +0800 CST

根据数据绘制颜色

  • 772

我想绘制一些数据,但颜色取决于某些条件。理想情况下,我想在plotly和matplotlib(单独的脚本)中执行此操作

数据

例如我有以下数据

import pandas as pd

data = {
    'X': [1, 2, 3, 4, 5,6,7,8,9,10],
    'Y': [5, 4, 3, 2, 1,2,3,4,5,5],
    'XL': [2,    None, 4,    None, None,None,4,5,None,3],
    'YL': [3,    None, 2,    None, None,None,5,6,None,4],
    'XR': [None, 4,    None, 1,    None,None,None,4,5,4],
    'YR': [None, 3,    None, 5,    None,None,None,3,4,4]
}

df = pd.DataFrame(data)

简单的情节

所以用 matplotlib

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

# Plot X, Y
ax.plot(df['X'], df['Y'], linestyle='-', marker='o')

# Update plot settings
ax.set_title('Trajectory Plot')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

# Show the plot
plt.show()

并有情节地

import plotly.graph_objects as go

# Create a scatter plot
fig = go.Figure(data=go.Scatter(x=df['X'], y=df['Y'], mode='lines+markers'))

# Update layout for better visibility
fig.update_layout(
    title='Trajectory Plot',
    xaxis_title='X-axis',
    yaxis_title='Y-axis',
)

# Show the plot
fig.show()

问题

我想修改脚本,以便我可以根据 和 对是否存在使用不同的(XL,YL)颜色(XR,YR)。

  • 灰色:不存在
  • 红色:仅存在XL、YL
  • 蓝色:仅存在XR、YR
  • 绿色:两者都存在

最后应该是这样的(原谅我画的很粗糙,我把原来的蓝线涂掉了)

如何在 matplotlib 和plotly 中添加它?

在此输入图像描述

python
  • 2 2 个回答
  • 33 Views

2 个回答

  • Voted
  1. Best Answer
    Suraj Shourie
    2023-11-28T11:32:37+08:002023-11-28T11:32:37+08:00

    IIUC您可以使用 matplotlib 的LineCollection ,请参阅此处的示例

    from matplotlib.collections import LineCollection
    from matplotlib.colors import BoundaryNorm, ListedColormap
    
    # COLOR map
    arr = np.array(['green']*len(df), dtype=str) # both exist # default
    arr[df['XL'].isna() & df['XR'].isna()] = 'grey' # none exist
    arr[~df['XL'].isna() & df['XR'].isna()] = 'red' # only L
    arr[df['XL'].isna() & ~df['XR'].isna()] = 'blue' # only R
    
    # generate line-segments
    points = np.array([df['X'], df['Y']]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    fig, ax = plt.subplots()
    lc = LineCollection(segments, colors=arr)
    
    lc.set_linewidth(2)
    line = ax.add_collection(lc)
    
    # add a scatter for point markers
    ax.scatter(df['X'], df['Y'], c=arr)
    
    ax.set_xlim(df['X'].min()-1, df['X'].max()+1)
    ax.set_ylim(df['Y'].min()-.1, df['Y'].max()+.1)
    plt.show()
    

    输出:

    在此输入图像描述

    对于情节,您可以拥有的最佳解决方案是:

    import plotly.graph_objects as go
    import itertools as it
    
    # create coordinate  pairs
    x_pairs = it.pairwise(df['X'])
    y_pairs = it.pairwise(df['Y'])
    
    # create base figure
    fig = go.Figure()
    
    # add traces (line segments)
    for x, y, color in zip(x_pairs, y_pairs, arr):
        fig.add_trace(
            go.Scatter(
                x=x,
                y=y, 
                mode='lines+markers', 
                line={'color': color}
            )
        )
        
    fig.update_layout(showlegend=False)
    

    输出:

    在此输入图像描述

    • 2
  2. atteggiani
    2023-11-28T11:13:11+08:002023-11-28T11:13:11+08:00

    一种解决方案是首先绘制整个数据集,而不使用标记。然后,最重要的是,根据您提到的条件绘制彩色标记。

    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    
    data = {
        'X': [1, 2, 3, 4, 5,6,7,8,9,10],
        'Y': [5, 4, 3, 2, 1,2,3,4,5,5],
        'XL': [2,    None, 4,    None, None,None,4,5,None,3],
        'YL': [3,    None, 2,    None, None,None,5,6,None,4],
        'XR': [None, 4,    None, 1,    None,None,None,4,5,4],
        'YR': [None, 3,    None, 5,    None,None,None,3,4,4]
    }
    
    df = pd.DataFrame(data)
    
    grey_cond = (df['XL'].isnull() | df['YL'].isnull()) & (df['XR'].isnull() | df['YR'].isnull())
    red_cond = (df['XL'].notnull() & df['YL'].notnull()) & (df['XR'].isnull() | df['YR'].isnull())
    blue_cond = (df['XR'].notnull() & df['YR'].notnull()) & (df['XL'].isnull() | df['YL'].isnull())
    green_cond = df['XR'].notnull() & df['YR'].notnull() & df['XL'].notnull() & df['YL'].notnull()
    
    fig, ax = plt.subplots()
    
    # Plot X, Y
    ax.plot(df['X'], df['Y'], linestyle='-', color='black')
    # Grey condition (none exist)
    ax.plot(df['X'][grey_cond], df['Y'][grey_cond],
        color='None',
        marker='o',
        markeredgecolor='grey',
        markerfacecolor='grey'
    )
    # Red condition (only XL, YL exist)
    ax.plot(df['X'][red_cond], df['Y'][red_cond],
        color='None',
        marker='o',
        markeredgecolor='red',
        markerfacecolor='red'
    )
    # Blue condition (only XR, YR exist)
    ax.plot(df['X'][blue_cond], df['Y'][blue_cond],
        color='None',
        marker='o',
        markeredgecolor='blue',
        markerfacecolor='blue'
    )
    # Green condition (Both exist)
    ax.plot(df['X'][green_cond], df['Y'][green_cond],
        color='None',
        marker='o',
        markeredgecolor='green',
        markerfacecolor='green'
    )
    
    # Update plot settings
    ax.set_title('Trajectory Plot')
    ax.set_xlabel('X-axis')
    ax.set_ylabel('Y-axis')
    
    # Show the plot
    plt.show()
    

    输出将如下所示: 输出图片

    这也没有彩色线条,但我认为这样应该更正确。否则,您必须选择要绘制与标记相同颜色的标记(数据点)的哪一侧(左侧或右侧)。

    label如果需要,您还可以通过添加到每个标记图来添加图例:

    fig, ax = plt.subplots()
    
    # Plot X, Y
    ax.plot(df['X'], df['Y'], linestyle='-', color='black',label="Trajectory")
    # Grey condition (none exist)
    ax.plot(df['X'][grey_cond], df['Y'][grey_cond],
        color='None',
        marker='o',
        markeredgecolor='grey',
        markerfacecolor='grey',
        label='Neither XL,YL nor XR,YR exist'
    )
    # Red condition (only XL, YL exist)
    ax.plot(df['X'][red_cond], df['Y'][red_cond],
        color='None',
        marker='o',
        markeredgecolor='red',
        markerfacecolor='red',
        label='Only XL,YL exist'
    )
    # Blue condition (only XR, YR exist)
    ax.plot(df['X'][blue_cond], df['Y'][blue_cond],
        color='None',
        marker='o',
        markeredgecolor='blue',
        markerfacecolor='blue',
        label='Only XR,YR exist'
    )
    # Green condition (Both exist)
    ax.plot(df['X'][green_cond], df['Y'][green_cond],
        color='None',
        marker='o',
        markeredgecolor='green',
        markerfacecolor='green',
        label='Both XL,YL and XR,YR exist'
    )
    
    # Update plot settings
    ax.set_title('Trajectory Plot')
    ax.set_xlabel('X-axis')
    ax.set_ylabel('Y-axis')
    plt.legend()
    plt.show()
    

    带有图例的输出将如下所示: 带图例的输出图

    希望这是有道理的

    干杯达维德

    • 0

相关问题

  • 如何将 for 循环拆分为 3 个单独的数据框?

  • 如何检查 Pandas DataFrame 中的所有浮点列是否近似相等或接近

  • “load_dataset”如何工作,因为它没有检测示例文件?

  • 为什么 pandas.eval() 字符串比较返回 False

  • Python tkinter/ ttkboostrap dateentry 在只读状态下不起作用

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    使用 <font color="#xxx"> 突出显示 html 中的代码

    • 2 个回答
  • Marko Smith

    为什么在传递 {} 时重载解析更喜欢 std::nullptr_t 而不是类?

    • 1 个回答
  • Marko Smith

    您可以使用花括号初始化列表作为(默认)模板参数吗?

    • 2 个回答
  • Marko Smith

    为什么列表推导式在内部创建一个函数?

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 个回答
  • Marko Smith

    为什么 'char -> int' 是提升,而 'char -> Short' 是转换(但不是提升)?

    • 4 个回答
  • Marko Smith

    为什么库中不调用全局变量的构造函数?

    • 1 个回答
  • Marko Smith

    std::common_reference_with 在元组上的行为不一致。哪个是对的?

    • 1 个回答
  • Marko Smith

    C++17 中 std::byte 只能按位运算?

    • 1 个回答
  • Martin Hope
    fbrereto 为什么在传递 {} 时重载解析更喜欢 std::nullptr_t 而不是类? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 您可以使用花括号初始化列表作为(默认)模板参数吗? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi 为什么列表推导式在内部创建一个函数? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A fmt 格式 %H:%M:%S 不带小数 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python C++20 的 std::views::filter 未正确过滤视图 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute 为什么 'char -> int' 是提升,而 'char -> Short' 是转换(但不是提升)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa 为什么库中不调用全局变量的构造函数? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis std::common_reference_with 在元组上的行为不一致。哪个是对的? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev 为什么编译器在这里错过矢量化? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan C++17 中 std::byte 只能按位运算? 2023-08-17 17:13:58 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve