显示一个条形图。

这是围绕st.altair_chart的语法糖。主要区别在于此命令使用数据自身的列和索引来确定图表的Altair规范。因此,在许多“只需绘制此图”的场景中,这更容易使用,但自定义性较差。

如果 st.bar_chart 没有正确猜测数据规范,请尝试使用 st.altair_chart 指定您想要的图表。

函数签名[source]

st.bar_chart(data=None, *, x=None, y=None, x_label=None, y_label=None, color=None, horizontal=False, stack=None, width=None, height=None, use_container_width=True)

参数

data (Anything supported by st.dataframe)

要绘制的数据。

x (str or None)

与x轴数据关联的列名或键。如果xNone(默认值),Streamlit将使用数据索引作为x轴值。

y (str, 字符串序列, 或 None)

与y轴数据相关联的列名或键。如果这是None(默认值),Streamlit 会将所有剩余列的数据绘制为数据系列。如果这是一个字符串Sequence,Streamlit 会在后台将您的宽格式表格转换为长格式表格,从而在同一图表上绘制多个系列。

x_label (str or None)

x轴的标签。如果这是None(默认),Streamlit将使用x中指定的列名(如果可用),否则将不显示标签。

y_label (str or None)

y轴的标签。如果这是None(默认值),Streamlit将使用y中指定的列名(如果有),否则将不显示标签。

color (str, tuple, Sequence of str, Sequence of tuple, or None)

The color to use for different series in this chart.

For a bar chart with just one series, this can be:

  • None, to use the default color.
  • A hex string like "#ffaa00" or "#ffaa0088".
  • An RGB or RGBA tuple with the red, green, blue, and alpha components specified as ints from 0 to 255 or floats from 0.0 to 1.0.

For a bar chart with multiple series, where the dataframe is in long format (that is, y is None or just one column), this can be:

  • None, to use the default colors.

  • The name of a column in the dataset. Data points will be grouped into series of the same color based on the value of this column. In addition, if the values in this column match one of the color formats above (hex string or color tuple), then that color will be used.

    For example: if the dataset has 1000 rows, but this column only contains the values "adult", "child", and "baby", then those 1000 datapoints will be grouped into three series whose colors will be automatically selected from the default palette.

    But, if for the same 1000-row dataset, this column contained the values "#ffaa00", "#f0f", "#0000ff", then then those 1000 datapoints would still be grouped into 3 series, but their colors would be "#ffaa00", "#f0f", "#0000ff" this time around.

For a bar chart with multiple series, where the dataframe is in wide format (that is, y is a Sequence of columns), this can be:

  • None, to use the default colors.
  • A list of string colors or color tuples to be used for each of the series in the chart. This list should have the same length as the number of y values (e.g. color=["#fd0", "#f0f", "#04f"] for three lines).

horizontal (bool)

是否使条形图水平显示。如果为False (默认),条形图将垂直显示。如果为True, Streamlit 将交换 x 轴和 y 轴,条形图将水平显示。

stack (bool, "normalize", "center", "layered", 或 None)

是否堆叠条形图。如果为 None(默认), Streamlit 使用 Vega 的默认值。其他值如下:

  • True: 条形图在图表中形成一个不重叠的、可叠加的堆叠。
  • False: 条形图并排显示。
  • "layered": 条形图相互重叠而不堆叠。
  • "normalize": 条形图堆叠,并且总高度被归一化为图表高度的 100%。
  • "center": 条形图堆叠并移动以使总高度围绕一个轴居中。

width (int or None)

图表所需的宽度,以像素表示。如果 widthNone(默认值),Streamlit 会根据绘图库将图表的宽度设置为适合其内容,最大不超过父容器的宽度。如果 width 大于父容器的宽度,Streamlit 会将图表宽度设置为与父容器的宽度匹配。

要使用 width,必须设置 use_container_width=False

height (int or None)

图表所需的高度,以像素表示。如果heightNone(默认值),Streamlit会根据绘图库自动调整图表的高度以适应其内容。

use_container_width (bool)

是否用父容器的宽度覆盖width。如果use_container_widthTrue(默认),Streamlit会将图表的宽度设置为与父容器的宽度匹配。如果use_container_widthFalse,Streamlit会根据width设置图表的宽度。

示例

import streamlit as st
import pandas as pd
import numpy as np

chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])

st.bar_chart(chart_data)

您还可以选择不同的列用于x和y,并根据第三列动态设置颜色(假设您的数据框是长格式):

import streamlit as st
import pandas as pd
import numpy as np

chart_data = pd.DataFrame(
    {
        "col1": list(range(20)) * 3,
        "col2": np.random.randn(60),
        "col3": ["A"] * 20 + ["B"] * 20 + ["C"] * 20,
    }
)

st.bar_chart(chart_data, x="col1", y="col2", color="col3")

如果你的数据框是宽格式的,你可以将多个列分组到 y 参数下,以显示不同颜色的多个系列:

import streamlit as st
import pandas as pd
import numpy as np

chart_data = pd.DataFrame(
    {
        "col1": list(range(20)),
        "col2": np.random.randn(20),
        "col3": np.random.randn(20),
    }
)

st.bar_chart(
    chart_data,
    x="col1",
    y=["col2", "col3"],
    color=["#FF0000", "#0000FF"],  # Optional
)

你可以旋转你的条形图以水平显示。

import streamlit as st
from vega_datasets import data

source = data.barley()

st.bar_chart(source, x="variety", y="yield", color="site", horizontal=True)

你可以将你的条形图进行解堆叠。

import streamlit as st
from vega_datasets import data

source = data.barley()

st.bar_chart(source, x="year", y="yield", color="site", stack=False)

将数据框连接到当前数据框的底部。

函数签名[source]

element.add_rows(data=None, **kwargs)

参数

data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None)

要连接的表格。可选。

**kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None)

要连接的有名称的数据集。可选。你只能传入1个数据集(包括在data参数中的那个)。

示例

import streamlit as st
import pandas as pd
import numpy as np

df1 = pd.DataFrame(
    np.random.randn(50, 20), columns=("col %d" % i for i in range(20))
)

my_table = st.table(df1)

df2 = pd.DataFrame(
    np.random.randn(50, 20), columns=("col %d" % i for i in range(20))
)

my_table.add_rows(df2)
# Now the table shown in the Streamlit app contains the data for
# df1 followed by the data for df2.

你可以对图表做同样的事情。例如,如果你想在折线图中添加更多数据:

# Assuming df1 and df2 from the example above still exist...
my_chart = st.line_chart(df1)
my_chart.add_rows(df2)
# Now the chart shown in the Streamlit app contains the data for
# df1 followed by the data for df2.

对于数据集已命名的图表,您可以使用关键字参数传递数据,其中键是名称:

my_chart = st.vega_lite_chart(
    {
        "mark": "line",
        "encoding": {"x": "a", "y": "b"},
        "datasets": {
            "some_fancy_name": df1,  # <-- named dataset
        },
        "data": {"name": "some_fancy_name"},
    }
)
my_chart.add_rows(some_fancy_name=df2)  # <-- name used as keyword
forum

还有问题吗?

我们的 论坛 充满了有用的信息和Streamlit专家。