Gradio 月活用户突破一百万!
了解更多Gradio 月活用户突破一百万!
了解更多数据可视化是数据分析和机器学习的关键方面。Gradio 的 DataFrame
组件是在 Web 应用程序中显示表格数据的常用方法。
但是,如果您想设置数据表格的样式怎么办?如果您想添加背景颜色、部分高亮单元格或更改数字的显示精度怎么办?本指南为您解答!
让我们开始吧!
前提条件:我们的示例将使用 gradio.Blocks
类。如果您还不熟悉它,可以先阅读 Blocks 指南。另请确保您使用的是最新版本的 Gradio:pip install --upgrade gradio
。
Styler
(样式器)Gradio DataFrame
组件现在支持 pandas
类的 Styler
类型的值。这使我们可以重用 Styler
类丰富的现有 API 和文档,而无需自行发明新的样式格式。这是一个完整的示例,展示了它的外观
import pandas as pd
import gradio as gr
# Creating a sample dataframe
df = pd.DataFrame({
"A" : [14, 4, 5, 4, 1],
"B" : [5, 2, 54, 3, 2],
"C" : [20, 20, 7, 3, 8],
"D" : [14, 3, 6, 2, 6],
"E" : [23, 45, 64, 32, 23]
})
# Applying style to highlight the maximum value in each row
styler = df.style.highlight_max(color = 'lightgreen', axis = 0)
# Displaying the styled dataframe in Gradio
with gr.Blocks() as demo:
gr.DataFrame(styler)
demo.launch()
Styler 类可用于将条件格式和样式应用于数据表格,使其在视觉上更具吸引力且更易于理解。您可以高亮显示某些值、应用渐变,甚至可以使用自定义 CSS 来设置 DataFrame 的样式。Styler 对象应用于 DataFrame,并返回一个具有相关样式属性的新对象,然后可以直接预览该对象,或在 Gradio 界面中动态呈现。
要了解有关 Styler 对象的更多信息,请阅读官方 pandas
文档: https://pandas.ac.cn/docs/user_guide/style.html
下面,我们将探讨几个示例
好的,让我们回顾一下之前的示例。我们首先创建一个 pd.DataFrame
对象,然后用浅绿色高亮显示每行中的最高值
import pandas as pd
# Creating a sample dataframe
df = pd.DataFrame({
"A" : [14, 4, 5, 4, 1],
"B" : [5, 2, 54, 3, 2],
"C" : [20, 20, 7, 3, 8],
"D" : [14, 3, 6, 2, 6],
"E" : [23, 45, 64, 32, 23]
})
# Applying style to highlight the maximum value in each row
styler = df.style.highlight_max(color = 'lightgreen', axis = 0)
现在,我们只需将此对象传递到 Gradio DataFrame
中,就可以在 4 行 Python 代码中可视化我们色彩丰富的数据表格
import gradio as gr
with gr.Blocks() as demo:
gr.Dataframe(styler)
demo.launch()
效果如下
除了高亮单元格之外,您可能还想为单元格内的特定文本着色。以下是如何更改某些列的文本颜色
import pandas as pd
import gradio as gr
# Creating a sample dataframe
df = pd.DataFrame({
"A" : [14, 4, 5, 4, 1],
"B" : [5, 2, 54, 3, 2],
"C" : [20, 20, 7, 3, 8],
"D" : [14, 3, 6, 2, 6],
"E" : [23, 45, 64, 32, 23]
})
# Function to apply text color
def highlight_cols(x):
df = x.copy()
df.loc[:, :] = 'color: purple'
df[['B', 'C', 'E']] = 'color: green'
return df
# Applying the style function
s = df.style.apply(highlight_cols, axis = None)
# Displaying the styled dataframe in Gradio
with gr.Blocks() as demo:
gr.DataFrame(s)
demo.launch()
在此脚本中,我们定义了一个自定义函数 highlight_cols,该函数将所有单元格的文本颜色更改为紫色,但对于 B、C 和 E 列,则覆盖为绿色。效果如下
有时,您处理的数据可能包含很长的浮点数,为了简单起见,您可能只想显示固定的小数位数。pandas Styler 对象允许您格式化显示的数字的精度。以下是如何做到这一点
import pandas as pd
import gradio as gr
# Creating a sample dataframe with floating numbers
df = pd.DataFrame({
"A" : [14.12345, 4.23456, 5.34567, 4.45678, 1.56789],
"B" : [5.67891, 2.78912, 54.89123, 3.91234, 2.12345],
# ... other columns
})
# Setting the precision of numbers to 2 decimal places
s = df.style.format("{:.2f}")
# Displaying the styled dataframe in Gradio
with gr.Blocks() as demo:
gr.DataFrame(s)
demo.launch()
在此脚本中,Styler 对象的 format 方法用于将数字的精度设置为两位小数。现在看起来更简洁了
到目前为止,我们一直将自己限制在 Pandas Styler
类支持的样式设置中。但是,如果您想创建自定义样式,例如根据单元格的值部分高亮显示单元格,该怎么办?
这在 Styler
中是不可能的,但是您可以通过创建自己的 styling 数组来实现,styling 数组是一个与您的数据大小和形状相同的二维数组。此列表中的每个元素都应是一个 CSS 样式字符串(例如“background-color: green”),它应用于包含单元格值的 <td>
元素(如果不需要应用自定义 CSS,则为空字符串)。同样,您可以创建一个 display_value 数组,该数组控制每个单元格中显示的值(该值可能与用于搜索/排序的底层值不同)。
这是如何在 `gr.Dataframe` 中使用自定义样式的完整代码,如上面的屏幕截图所示
import gradio as gr
data = [
["DeepSeek Coder", 79.3],
["Llama 3.3", 68.9],
["Qwen 2.5", 61.9],
["Gemma 2", 59.5],
["GPT 2", 18.3],
]
headers = ["Model", "% Correct (LeetCode Hard)"]
def get_styling(values):
return [["", f"background: linear-gradient(90deg, rgba(220, 242, 220) {row[1]}%, transparent {row[1]}%)"] for row in values]
def get_display_value(values):
display_values = []
medals = ["🥇", "🥈", "🥉"]
for i, row in enumerate(values):
if i < 3:
display_values.append([f"{medals[i]} {row[0]}", row[1]])
else:
display_values.append([row[0], row[1]])
return display_values
styling = get_styling(data)
display_value = get_display_value(data)
value = {
"data": data,
"headers": headers,
"metadata": {
"styling": styling,
"display_value": display_value,
},
}
with gr.Blocks() as demo:
gr.Dataframe(value, show_search="search")
demo.launch()
需要注意的一点是,gradio 的 DataFrame
组件仅在非交互模式(即“静态”模式)下接受自定义样式对象。如果 DataFrame
组件是交互式的,则样式信息将被忽略,而会显示原始表格值。
默认情况下,DataFrame
组件是非交互式的,除非它被用作事件的输入。在这种情况下,您可以通过设置 interactive
属性来强制组件变为非交互式,如下所示:
c = gr.DataFrame(styler, interactive=False)
这只是使用 pandas
的 Styler
类与 gradio.DataFrame
组件可以实现的冰山一角。请尝试一下,并告诉我们您的想法!