我想为牛郎图的箱形图设置黑色边界 colored颜色 ,我try 在编码通道上将笔画参数添加到黑色,但这将我的红色中线覆盖为黑色.

这是我正在try 的代码:

def plot_hourly_boxplot_altair(data, column, session_state=None):
    # Convert 'fecha' column to datetime format
    data['fecha'] = pd.to_datetime(data['fecha'])
    
    # Filter out rows where the specified column has NaN values
    data = data.dropna(subset=[column])

    if session_state and not session_state.zero_values:
        # Erase 0 values from the data
        data = data[data[column] != 0]

    # filter the data to just get the date range selected
    data = range_selector(data, min_date=session_state.min_date, max_date=session_state.max_date)

    # filter the data to just get the days of the week selected
    if session_state.days:
        data = data[data['fecha'].dt.dayofweek.isin(session_state.days)]

    if data.empty:
        print(f"No valid data for column '{column}'.")
        return None

    # Create a boxplot using Altair with x axis as the hour of the day on 24 h format and
    # y axis as the demand that is on the data[column]
    data['fecha'] = data['fecha'].dt.strftime('%Y-%m-%dT%H:%M:%S') 
          
    boxplot = alt.Chart(data).mark_boxplot(size = 23,median={'color': 'red'}).encode(
        x=alt.X('hours(fecha):N', title='Hora', axis=alt.Axis(format='%H'), sort='ascending'),
        y=alt.Y(f'{column}:Q', title='Demanda [kW]'),
        stroke = alt.value('black'),  # Set thke color of the boxplot
        strokeWidth=alt.value(1),  # Set the width of the boxplot
        # color=alt.value('#4C72B0'),  # Set the color of the boxplot
        color=alt.value('#2d667a'),  # Set the color of the bars
        opacity=alt.value(1),  # Set the opacity of the bars           
        tooltip=[alt.Tooltip('hours(fecha):N', title='Hora')]  # Customize the tooltip
    )
    chart = (boxplot).properties(
        width=600,  # Set the width of the chart
        height=600,  # Set the height of the chart
        title=(f'Boxplot de demanda de potencia {column}')  # Remove date from title
    ).configure_axis(
        labelFontSize=12,  # Set the font size of axis labels
        titleFontSize=14,  # Set the font size of axis titles
        grid=True,
        # color of labels of x-axis and y-axis is black
        labelColor='black',
        # x-axis and y-axis titles are bold
        titleFontWeight='bold',
        # color of x-axis and y-axis titles is black
        titleColor='black',
        gridColor='#4C72B0',  # Set the color of grid lines
        gridOpacity=0.2  # Set the opacity of grid lines
    ).configure_view(
        strokeWidth=0,  # Remove the border of the chart
        fill='#FFFFFF'  # Set background color to white
    )

    return chart  # Enable zooming and panning

这是我的结果:

boxplot with black border but black median line too

我try 使用以下代码进行条件笔画:

        stroke=alt.condition(
            alt.datum._argmax == 'q3',  # condition for the stroke color (for the box part)
            alt.value('black'),         # color for the stroke
            alt.value('red')            # color for the median line
        ),

但中间和边界变成红色,如图所示:

border and median line red

我怎样才能实现我的目标?即红色中线和黑色边界.我还在牛郎星文件上看到了这条注释

注意:笔画编码的优先级高于 colored颜色 编码,因此如果指定了冲突的编码,则可能会覆盖 colored颜色 编码.

有什么方法可以做到这一点吗?

推荐答案

您可以set the properties of the box components inside mark_boxplot as mentioned here in the docs,而不是通过编码:

import altair as alt
from vega_datasets import data

source = data.cars()

alt.Chart(source).mark_boxplot(
    color='lightblue',
    box={'stroke': 'black'},  # Could have used MarkConfig instead
    median=alt.MarkConfig(stroke='red'),  # Could have used a dict instead
).encode(
    alt.X("Miles_per_Gallon:Q").scale(zero=False),
    alt.Y("Origin:N"),
)

enter image description here

使用MarkConfig而不是dict的优点是您可以在帮助弹出窗口中查看所有可用的参数名称.

Python相关问答推荐

tempfile.mkstemp(text=.)参数实际上是什么?

Python:根据创建时间合并两个收件箱

在Python中添加期货之间的延迟

脚注在Python中使用regex导致错误匹配

如何将不同长度的新列添加到现有的框架中

NumPy中的右矩阵划分,还有比NP.linalg.inv()更好的方法吗?

如果索引不存在,pandas系列将通过索引获取值,并填充值

添加包含中具有任何值的其他列的计数的列

根据在同一数据框中的查找向数据框添加值

将数据框架与导入的Excel文件一起使用

Pandas - groupby字符串字段并按时间范围 Select

从dict的列中分钟

用NumPy优化a[i] = a[i-1]*b[i] + c[i]的迭代计算

Python,Fitting into a System of Equations

Django RawSQL注释字段

python中的解释会在后台调用函数吗?

Python中的变量每次增加超过1

如何更改groupby作用域以找到满足掩码条件的第一个值?

python中csv. Dictreader. fieldname的类型是什么?'

如何创建引用列表并分配值的Systemrame列