利用d3画柱状图

话不多说,直接上代码

<!DOCTYPE html>
<html lang="en">
<head>
    <title>BarChart</title>
    <script src="https://d3js.org/d3.v7.js"></script>
</head>
<body>
<svg width="1600" height="800" id="mainsvg" class="svgs">
</svg>

<script>
    const data = [{name: 'a', value: 6}, {name: 'b', value: 7}];

    const svg = d3.select('#mainsvg');//主画布

    const width = +svg.attr('width');
    const height = +svg.attr('height');//主画布的宽和高
    const margin = {top: 60, right: 30, bottom: 60, left: 50};//图表部分在主画布周围的留白宽度
    const innerWidth = width - margin.left - margin.right;
    const innerHeight = height - margin.top - margin.bottom;//图表部分的宽和高

    //x和y轴的比例尺,domain是指定响应的取值范围,range是指定实际在屏幕上的显示范围,比例尺是一个函数,可以将domain里特定的某一个值转化为屏幕上实际显示的位置
    const XScale = d3.scaleLinear()
        .domain([0, d3.max(data, d => d.value)])
        .range([0, innerWidth]);
    const YScale = d3.scaleBand()
        .domain(data.map(d => d.name))
        .range([0, innerHeight])
        .padding(0.1);//让每相邻的两个刻度之间有0.1的间距,防止画出来的柱状图连在一起

    const g = svg.append('g').attr('id', 'maingroup').attr('transform', `translate(${margin.left},${margin.top})`);

    const xAxis = d3.axisBottom(XScale);
    g.append('g').call(xAxis).attr('transform', `translate(0, ${innerHeight})`);
    const yAxis = d3.axisLeft(YScale);
    g.append('g').call(yAxis);

    data.forEach(d => {//对数据进行绘制
        g.append('rect')
            .attr('width', XScale(d.value))
            .attr('height', YScale.bandwidth())//比例尺自带的接口,返回每一个刻度的宽度
            .attr('fill', 'black')
            .attr('y', YScale(d.name));
    });

    d3.selectAll('.tick text').attr('font-size', '20');//刻度的字体大小调整
    g.append('text')//加一个图表的标题
        .text('TEST')
        .attr('font-size', '50')
        .attr('transform', `translate(${innerWidth / 2},0)`)
        .attr('text-anchor', 'middle');
</script>
</body>
</html>

效果如下
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是一个简单的例子,展示如何使用Python中的一些常用数据可视化库出雷达图、柱状图、词云和饼图,并创建数据可视化大屏: 1. 雷达图 ```python import matplotlib.pyplot as plt import numpy as np # 创建数据 categories = ['A', 'B', 'C', 'D', 'E'] values = [5, 3, 4, 2, 6] # 计算角度 angles = np.linspace(0, 2*np.pi, len(categories), endpoint=False) # 闭合图形 values = np.concatenate((values, [values[0]])) angles = np.concatenate((angles, [angles[0]])) # 创建雷达图 fig = plt.figure() ax = fig.add_subplot(111, polar=True) ax.plot(angles, values, 'o-', linewidth=2) ax.fill(angles, values, alpha=0.25) ax.set_thetagrids(angles * 180/np.pi, categories) ax.grid(True) # 显示图像 plt.show() ``` 2. 柱状图 ```python import matplotlib.pyplot as plt # 创建数据 x = ['A', 'B', 'C', 'D', 'E'] y = [5, 3, 4, 2, 6] # 创建柱状图 fig, ax = plt.subplots() ax.bar(x, y) # 添加标签和标题 ax.set_xlabel('Categories') ax.set_ylabel('Values') ax.set_title('Example Bar Chart') # 显示图像 plt.show() ``` 3. 词云 ```python from wordcloud import WordCloud import matplotlib.pyplot as plt # 创建词云 text = "Hello World! This is an example text for wordcloud." wordcloud = WordCloud().generate(text) # 显示词云 plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show() ``` 4. 饼图 ```python import matplotlib.pyplot as plt # 创建数据 labels = ['A', 'B', 'C', 'D', 'E'] sizes = [5, 3, 4, 2, 6] # 创建饼图 fig, ax = plt.subplots() ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90) # 添加标题 ax.set_title('Example Pie Chart') # 显示图像 plt.show() ``` 5. 创建数据可视化大屏 一般来说,创建数据可视化大屏需要用到前端技术和可视化库,比如D3.js、Echarts等。这里提供一个简单的Python库dash,可以用Python代码创建交互式的数据可视化大屏。 ```python import dash import dash_core_components as dcc import dash_html_components as html # 创建app app = dash.Dash() # 创建布局 app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='example-graph', figure={ 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Category 1'}, {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': 'Category 2'}, ], 'layout': { 'title': 'Example Dash Plot' } } ) ]) # 启动app if __name__ == '__main__': app.run_server(debug=True) ``` 上面的代码创建了一个简单的Dash应用,包括一个标题、一个段落和一个柱状图。你可以根据需要修改这个例子,添加更多的组件和布局,创建你需要的数据可视化大屏。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

最辣の鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值