如何在 MUI x-charts 条形图上放置圆角?

问题描述 投票:0回答:1

我使用 mui barchart 创建了一个图表,

import { BarChart } from '@mui/x-charts/BarChart';
import { ThemeProvider, createTheme, useTheme } from '@mui/material/styles';

我想给这些条形做圆角。我尝试使用 borderRadius 来获取 sx 属性和系列属性。但没有成功。 sx 属性在图表周围创建边框,而不是为每个柱形图创建边框。 到目前为止我有以下代码:

 <ThemeProvider theme={darkTheme}  >
    <BarChart
       
        sx={[{p: 5, border: 1, borderRadius: 3}]}
        yAxis={[
              {
               id: 'barCategories',
               data: ['A', 'B', 'C', 'D', 'E'],
               scaleType: 'band',
              },
         ]}
         series={[
                {
                 data: [50, 20, 85, 60, 20],
                 color: '#fff',
                },
                            
          ]}
          layout="horizontal"
     />
</ThemeProvider>

它看起来像这样:

如何使条形看起来像这样圆角:

reactjs charts material-ui rounded-corners
1个回答
0
投票

由于 MUI Bar Charts 的底层元素是 SVG rect 元素,因此您将无法应用 CSS

border-radius
。但是您可以提供自己的自定义
Bar
组件
,而不是渲染
rect
元素,而是渲染一个
path
元素,显示为带圆角的矩形,并通过
slots
属性传递该元素。

例如:

<BarChart
  ...
  layout="horizontal"
  slots={{
    bar: (props) => {
      const radius = 7;
      const {x, y, height, width, ownerState, ...restProps} = props
      
      // Path of a rectangle with rounded corners on the right
      // for horizontal layout
      const d = `M${x},${y}h${width - radius}a${radius},${radius} 0 0 1 ${radius},${radius}v ${height - 2 * radius}a${radius},${radius} 0 0 1 ${-radius},${radius}h${radius - width}z`
      return <path d={d} fill={ownerState.color}
      {...restProps} />
    }
  }}
    />

产生:

(我会记下这一点以获得更好的性能 - 这个演示只是为了让您滚动。)

工作 CodeSanbox: https://codesandbox.io/s/mui-bar-chart-with-rounded-corders-right-zms2m5?file=/Demo.js

© www.soinside.com 2019 - 2024. All rights reserved.