• plotly数据科学交互式可视化,Python

    千次阅读 2019-12-23 00:35:08



    pip install plotly



    import plotly as py
    import plotly.graph_objs as go
    import numpy as np
    if __name__ == '__main__':
        count = 20
        x = np.linspace(0, 5, count)  # 随机生成count个0到5之间的数
        y0 = np.random.randn(count) + 8
        y1 = np.random.randn(count)
        y2 = np.random.randn(count) - 8
        trace0 = go.Scatter(
            mode='markers',  # 散点,没有线
            name='散点'  # 曲线名称
        trace1 = go.Scatter(
            mode='lines+markers',  # 散点+线
                size=15,  # 点的大小
                color='rgba(255, 180, 190, .6)',  # 颜色。最后一位是透明度
                    width=2,  # 线的宽度
                    color='rgb(0, 255, 0)'  # 线的颜色
        trace2 = go.Scatter(
            mode='lines',  # 线
                width=4,  # 线宽
        data = [trace0, trace1, trace2]
        py.offline.plot(data, filename='fig.html')






    [ 7.149432    6.50489461  7.16456305  7.45697682  7.36924142  8.87313759
      7.57906709  9.32564909  9.83994729  7.86031166  7.50424235  8.00859527
      8.03884244  8.24660839  7.74482351  7.10029204  7.38240537  8.37656517
     10.25392977  7.69139566]
    [-0.20807945 -1.87541628 -2.1628432   2.02659036 -0.64169184 -0.89742978
     -1.11686915 -0.78583164 -1.60748698 -1.5941247   0.87648078 -0.57077708
      0.09552706 -0.41319839 -0.11193602 -0.51171773  0.20090277 -0.81025678
      0.09127885  0.64375603]
    [ -7.49336588  -7.98602767  -9.99411645 -11.25695211  -8.35283071
      -8.17732449  -7.9029906   -7.01508945  -8.05447955  -9.73398467
      -9.17156658  -7.43255481  -7.68744518  -8.54303014  -7.5810631
      -8.98659986  -8.19372767  -9.24647112  -7.31539077  -9.57868002]


  • 基于plotly数据可视化The amount of data in the world is growing every second. From sending a text to clicking a link, you are creating data points for companies to use. Insights that can be drawn from ...


    The amount of data in the world is growing every second. From sending a text to clicking a link, you are creating data points for companies to use. Insights that can be drawn from this collection of data can be extremely valuable. Every business has their own storage of data that they need to examine. One of the most important ways this examination is done is by visualizing the data.

    吨他达到世界数据的增长每一秒。 从发送文本到单击链接,您正在创建供公司使用的数据点。 从这些数据收集中得出的见解可能非常有价值。 每个企业都有自己需要检查的数据存储。 进行此检查的最重要方法之一是可视化数据。

    为什么要可视化数据? (Why Visualize Data?)

    Simply put — “a picture is worth a thousand words”. In the entire history of business, data visualization has remained a necessary component. The reason it is so necessary is ultimately because we are visual creatures. Why else do you think a majority of us would prefer to watch a movie adaptation of a book than read the book itself? In terms of business presentations, a graph or chart of sales data may prove more insightful than just plain text. It is easy to draw insights from visual mediums rather than word documents.

    简而言之-“ 一张图片值得一千个字 ”。 在整个业务历史中,数据可视化仍然是必不可少的组成部分。 之所以如此必要,是因为我们最终是视觉生物。 您为什么还认为我们大多数人宁愿看电影改编电影也不愿看书本身? 就业务演示而言,销售数据的图形或图表可能会证明比纯文本更具洞察力。 从视觉媒介而不是单词文档中汲取见解很容易。

    By visualizing the data you are making the data more accessible to a wider audience. This can help draw more insights because someone else might have an insight or two that you may never have thought of. The more people that see your visualization, then the more insights can potentially be made.

    通过可视化数据,您可以使更广泛的受众更容易访问数据。 这可以帮助您获得更多的见解,因为其他人可能有您可能从未想过的一两个见识。 看到您的可视化内容的人越多,则可以潜在地获得更多的见解。

    Image for post
    Photo by Austin Distel on Unsplash
    Austin DistelUnsplash拍摄的照片

    Visualizations also play a key role when presenting to crucial decision makers such as board members or shareholders. As you are constructing your numerous graphs and plots to highlight key data points, the visuals you decide to make can help push these decision makers in one direction or another. If the data visuals are presented with a select narrative in mind, then these decision makers will be inclined to make specific decisions based on your presentation.

    在向关键决策者(例如董事会成员或股东)展示时,可视化也起着关键作用。 在构建大量图形和图表以突出显示关键数据点时,您决定制作的视觉效果可以帮助将这些决策者推向一个方向或另一个方向。 如果在呈现数据视觉效果时考虑了特定的叙述,那么这些决策者将倾向于根据您的呈现做出特定的决策。

    数据可视化工具 (Tools for Data Visualization)

    Pie charts, bar charts, line graphs, and so on are all effective visuals when presenting data. These visuals are the tried and true forms for data presentation and we have made it even easier to create them. What we once use to do by hand can now be done with a couple of clicks on a computer.

    饼图,条形图,折线图等都是呈现数据时的有效视觉效果。 这些视觉效果是经过验证的真实数据展示形式,我们使创建它们变得更加容易。 现在,我们曾经手动执行的操作现在只需在计算机上单击几下即可完成。

    Nowadays, we have access to multiple programs to construct beautiful looking charts and graphs. These tools range from more technically based applications of visualization like Python’s Matplotlib or Plotly to more user-friendly ones like Tableau or Microsoft Power BI. Data visualizations tools are now more accessible than ever before.

    如今,我们可以使用多个程序来构建美观的图表。 这些工具的范围从更基于技术的可视化应用程序(例如Python的MatplotlibPlotly)到更加用户友好的工具(如TableauMicrosoft Power BI) 。 数据可视化工具现在比以往任何时候都更易于访问。

    Image for post
    Photo by Katie Rodriguez on Unsplash
    凯蒂·罗德里格斯 ( Katie Rodriguez)Unsplash上的 照片

    Within the realm of Python programming, there are many different libraries you could use to craft data visualizations. These libraries include, but are not limited, to Altair, Seaborn, and Plotly. There is no superior Python library because it all depends on what you are comfortable with and the problem or data you are trying to visualize.

    在Python编程领域内,可以使用许多不同的库来制作数据可视化。 这些库包括但不限于AltairSeabornPlotly 。 没有出色的Python库,因为这一切都取决于您是否熟悉什么以及要可视化的问题或数据。

    学习如何使用情节 (Learning How to Use Plotly)

    One of the tools we mentioned before is called Plotly. Plotly is a graphing and plotting library in Python similar to Matplotlib. The difference between the two is the fact that Plotly creates dynamically, interactive charts and graphs.

    我们之前提到的工具之一称为Plotly 。 Plotly是Python中的绘图和绘图库,类似于Matplotlib。 两者之间的区别在于Plotly创建动态的交互式图表的事实。

    一个简单的业务问题 (A Simple Business Problem)

    To get started with Plotly, we will need data to graph or plot first. So let’s say for example you work for a business that sells clothing. They want you to chart the sales for their shirts and jeans over the course of one year and have provided you with the data to do so. This problem will help us begin working with Plotly.

    要开始使用Plotly,我们将需要首先绘制图形或绘图的数据。 举例来说,假设您为一家销售服装的公司工作。 他们希望您绘制一年中衬衫和牛仔裤的销售图表,并提供了相关数据。 这个问题将帮助我们开始使用Plotly。

    剧情安装 (Installing Plotly)

    In order to begin, we must first install Plotly by using the following command in your terminal:


    $ pip install plotly

    Or if you have Anaconda installed:


    $ conda install -c plotly plotly

    导入 (Importing Plotly)

    Now that you have Plotly installed, let’s open a new file and start importing the necessary libraries for our data visualization example:


    import plotly.express as px
    import calendar as cal
    import random
    import pandas as pd

    Here we are using plotly.express, which is a module within Plotly that will quickly create graphs and charts for us.

    在这里,我们使用plotly.express ,它是plotly.express中的一个模块,可以为我们快速创建图形和图表。

    创建数据 (Creating the Data)

    Since we are not actually given real data, we will have to create our own:


    data = {'Months': [cal.month_name[i] for i in range(1,13)],
    'Shirts': [round(random.gauss(100, 15)) for _ in range(12)],
    'Jeans': [round(random.gauss(50, 20)) for _ in range(12)]}

    Plotly works very well with Pandas DataFrames so we will store our newly created data into a DF:

    Plotly与Pandas DataFrames配合得很好,因此我们会将新创建的数据存储到DF中:

    df = pd.DataFrame(data)

    This new DF looks like this:


    Image for post
    Our DF for Plotly

    情节的条形图 (Plotly’s Bar Chart)

    Now that we have our DF ready we can begin crafting our bar chart:


    fig = px.bar(df, 

    Here we are using the .bar() method and inputting the DF of our data, and specifying the x and y axes. We are crafting a stacked bar chart by making a list for the columns: ‘Shirts’ and ‘Jeans’. Which we’ll display by calling fig.show().

    在这里,我们使用.bar()方法并输入数据的DF,并指定xy轴。 我们通过列出以下列的列表来制作堆叠式条形图:“ Shirts ”和“ Jeans ”。 我们将通过调用fig.show()显示。

    Image for post

    Success! That was simple enough. The cool thing about this Plotly chart is that you can start interacting with it by zooming in, panning, etc. But in regards to the overall chart, there are some things we would like to change to make this graph a little bit more descriptive like adding a title and renaming a few of the labels.

    成功! 那很简单。 关于该Plotly图表,最酷的事情是您可以通过放大,平移等开始与之交互。但是对于整体图表,我们需要进行一些更改以使该图表更具描述性,例如添加标题并重命名一些标签。

    fig = px.bar(df, 
    title='Total Monthly Item Sales',
    labels={'variable': 'Item',
    'value': 'Quantity Sold (in thousands)'})fig.show()

    The difference between this code and the code before is the addition of the title= and labels={} argument. With these new arguments we are adding in a title for the chart and under the labels we are basically using a dictionary to replace the two current labels.

    此代码与之前的代码之间的区别是添加了title=labels={}参数。 通过这些新参数,我们为图表添加了一个标题,在labels之下,我们基本上是使用字典来替换两个当前标签。

    Image for post
    Updated bar chart with correct labels and title

    Now that the bar chart is properly labeled, we are basically finished with using Plotly for this data. But what if we wanted to do other kinds of charts or graphs in order to view different sides of the data?

    现在,条形图已正确标记,我们基本上已经完成了对数据使用Plotly的操作。 但是,如果我们想做其他种类的图表来查看数据的不同方面怎么办?

    情节的线图 (Plotly’s Line Graph)

    Plotly allows us to create other types of visualizations too. We can easily create a line graph by using the code from before and just changing one thing:

    通过Plotly,我们也可以创建其他类型的可视化。 我们可以使用之前的代码轻松地创建折线图,而只需更改一件事:

    fig = px.line(df, 
    title='Monthly Item Sales',
    labels={'variable': 'Item',
    'value': 'Quantity Sold (in thousands)'})fig.show()

    All we did here was change px.bar to px.line. This now displays the following:

    我们在这里所做的只是将px.bar更改为px.line 。 现在将显示以下内容:

    Image for post
    A line graph with the same data

    Now we have a line graph! But wait there’s more…

    现在我们有了折线图! 但是,等等……

    情节饼图 (Plotly’s Pie Chart)

    Let’s say we wanted to compare how many shirts were sold vs how many jeans were sold in the entire year.


    First, we must change our data to show the total sum of all sales for shirts and jeans:


    pie_df = df[['Shirts','Jeans']].sum()

    Here we’re just getting the sum of both Shirts and Jeans from the DF. Then, we will need to use px.pie() using our new summed up DF.

    在这里,我们只是从DF中获取ShirtsJeans的总和。 然后,我们需要使用新的汇总DF使用px.pie()

    fig = px.pie(values=pie_df.values, 
    title="Sales Percentage in a Year")fig.show()

    The argument values is used to determine the sizes of each portion of the pie chart. The names are the labels for each of the portions.

    参数values用于确定饼图各部分的大小。 names是每个部分的标签。

    Image for post
    Our pie chart of the data

    Awesome! Now we have created three different types of visualizations for our data. But you don’t have to stop — there are more options available (see here for more) if you feel the need to continue experimenting with Plotly.

    太棒了! 现在,我们为数据创建了三种不同类型的可视化。 但是您不必停下来-如果您有需要继续尝试Plotly的权利,可以使用更多选项( 有关更多信息, 请参见此处 )。

    数据见解和结论 (Data Insights and Conclusions)

    After visualizing our data, we would need to come to some sort of insight or conclusion based on the visuals. What can you tell based on these charts? Are there some obvious conclusions that can be drawn? What about some not so obvious ones?

    可视化我们的数据后,我们需要根据视觉效果得出某种见解或结论。 您可以根据这些图表看出什么? 是否可以得出一些明显的结论? 那些不太明显的东西呢?

    Anyways, insights and conclusions are easier to see rather than read. If you are still wondering about the importance of visualizations, then just take a look back at the DF we created and compare it to any of the visuals we created with Plotly. Sometimes reading information is not as good as seeing the information.

    无论如何,见解和结论更容易看到而不是阅读。 如果您仍然想知道可视化的重要性,那么只需回顾一下我们创建的DF,并将其与我们使用Plotly创建的任何可视化图像进行比较。 有时阅读信息不如阅读信息。

    翻译自: https://towardsdatascience.com/how-to-use-plotly-for-data-visualization-f3d62bbcfd92


  • 交互式数据可视化 简介(我们将创建的内容): (Introduction (what we’ll create):) Plotly is the library that has set the benchmark for interactivity for all the available map-visualization python ...


    简介(我们将创建的内容): (Introduction (what we’ll create):)

    Plotly is the library that has set the benchmark for interactivity for all the available map-visualization python libraries. It is based on the JavaScript library D3.js. There’s hardly anything you can’t do with Plotly. Display data on hover, zoom into the map, pan the map, add buttons and sliders, create live animations, and the list goes on.

    Plotly是为所有可用的地图可视化python库设置了交互性基准的库。 它基于JavaScript库D3.js。 使用Plotly几乎没有什么可以做的。 在悬停上显示数据,放大地图,平移地图,添加按钮和滑块,创建实时动画,然后列表继续。

    This tutorial will introduce Plotly. We will make a Choropleth visualization in this tutorial, like the one shown below. However, Plotly can be used equally well for creating scatter visualizations. We will cover scatter visualizations using Plotly in the ‘Plotly + Mapbox’ tutorial and the ‘Plotly + Datashader’ tutorial.

    本教程将介绍Plotly。 我们将在本教程中进行Choropleth可视化,如下图所示。 但是,Plotly可以很好地用于创建散点图。 我们将在“ Plotly + Mapbox”教程“ Plotly + Datashader”教程中使用Plotly涵盖散点图。

    本教程的结构: (Structure of the tutorial:)

    The tutorial is structured into the following sections:


    1. Pre-requisites


    2. Installing Plotly


    3. Converting shapefile to GeoJSON


      Converting shapefile to GeoJSON




      Method 1: Using OGR


      Method 1: Using OGR




      Method 2: Using GeoPandas


    4. Getting started with the tutorial


    5. When to use this library


    先决条件: (Pre-requisites:)

    This tutorial assumes that you are familiar with python and that you have python downloaded and installed in your machine. If you are not familiar with python but have some experience of programming in some other languages, you may still be able to follow this post, depending on your proficiency.

    本教程假定您熟悉python,并且已在计算机中下载并安装了python。 如果您不熟悉python,但有一些使用其他语言进行编程的经验,则根据您的熟练程度,仍然可以继续阅读此文章。

    It is recommended, but not necessary, that you go through the GeoPandas tutorial to get an overall idea of shapefiles.


    Plotly安装: (Installing Plotly:)

    If you are using Anaconda, you can run:


    conda install -c plotly plotly=4.8.1

    Otherwise, you can try the pip installer:


    pip install plotly==4.8.1

    For more information related to the installation, you can see https://plotly.com/python/getting-started/


    将shapefile转换为GeoJSON: (Converting shapefile to GeoJSON:)

    Unlike GeoPandas, plotly doesn’t read shapefiles. Instead, it requires a GeoJSON file for reading the geometry and attributes of the relevant shapes. If you have a GeoJSON file available, you can skip this section.

    与GeoPandas不同,plotly不读取shapefile。 相反,它需要一个GeoJSON文件来读取相关形状的几何形状和属性。 如果您有可用的GeoJSON文件,则可以跳过此部分。

    If you don’t have a GeoJSON file directly, you can convert a shapefile to GeoJSON.


    We will discuss two methods of converting a shapefile to GeoJSON.


    方法1:使用OGR (Method 1: Using OGR)

    This is the method that has been shown in the notebook. It makes use of the Geospatial Data Abstraction Library (GDAL). Actually, to be more specific, it makes use of the OGR library, which comes along with GDAL, to perform manipulations on geospatial vector data. For more information on GDAL, see https://pypi.org/project/GDAL/.

    这是笔记本中显示的方法。 它利用了地理空间数据抽象库(GDAL)。 实际上,更具体地说,它利用GDAL附带的OGR库对地理空间矢量数据执行操作。 有关GDAL的更多信息,请参见https://pypi.org/project/GDAL/

    Once you have GDAL installed, import ogr and call the ESRI Shapefile driver.

    安装GDAL后,导入ogr并调用ESRI Shapefile驱动程序。

    import ogr#We used compressed shapefiles obtained from mapshaper.org
    driver = ogr.GetDriverByName('ESRI Shapefile')shp_path = 'shape_files\\India_States_2020_compressed\\India_states.shp'data_source = driver.Open(shp_path, 0)

    Here, you can see that we are using compressed shapefiles. This is because the visualizations generated by plotly tend to be very heavy, and their size is directly proportional to the size of the geospatial data. So if our shapefile size gets reduced by 50%, the visualization size also gets reduced by approximately the same proportion. So we took our original shapefiles and performed compression on them using the online tool https://mapshaper.org/. To know more about how to perform the conversions using mapshaper, click here. The compressed shapefile sizes are approximately 10% of the original.

    在这里,您可以看到我们正在使用压缩的shapefile。 这是因为通过散点图生成的可视化效果往往非常繁重,并且其大小与地理空间数据的大小成正比。 因此,如果我们的shapefile大小减少了50%,则可视化文件的大小也将减少大约相同的比例。 因此,我们采用了原始的shapefile,并使用在线工具https://mapshaper.org/对它们进行了压缩。 要了解有关如何使用mapshaper进行转换的更多信息, 请单击此处 。 压缩的shapefile大小约为原始大小的10%。

    Once we have the shapefiles opened, we extract the individual features (including geometry and attributes) and store them in the correct JSON format (this is done directly by the ExportToJson method). Once that is done, we dump the JSON file to local storage.

    打开shapefile后,我们将提取单个特征(包括几何和属性)并将其存储为正确的JSON格式(这直接由ExportToJson方法完成)。 完成后,我们将JSON文件转储到本地存储。

    fc = {
    'type': 'FeatureCollection',
    'features': []
    }lyr = data_source.GetLayer(0)
    for feature in lyr:
    fc['features'].append(feature.ExportToJson(as_object=True))with open('json_files\\India_States_2020_compressed.json', 'w') as f:
    json.dump(fc, f)

    方法2:使用GeoPandas (Method 2: Using GeoPandas)

    This method is much more straightforward.


    import geopandas as gpd# set the filepath and load
    fp = "shape_files\\India_States_2020_compressed\\India_States.shp"#reading the file stored in variable fp
    map_df = gpd.read_file(fp)#Export it as GeoJSON
    map_df.to_file("json_files\\India_States_2020_compressed_gpd.json", driver='GeoJSON')

    You just need to read the shapefile using GeoPandas and then export it to GeoJSON using a single line, by specifying the driver as ‘GeoJSON’. However, the GeoJSON files created with this method tend to be slightly larger in size. For instance, for the same shapefile, the GeoJSON file created using OGR was 800 KB large while the one created using GeoPandas was 900 KB large. That’s about a 12.5% higher size using GeoPandas.

    您只需要使用GeoPandas读取shapefile,然后通过将驱动程序指定为'GeoJSON',即可使用一行将其导出到GeoJSON。 但是,使用此方法创建的GeoJSON文件的大小往往会稍大。 例如,对于同一个shapefile,使用OGR创建的GeoJSON文件大800 KB,而使用GeoPandas创建的GeoJSON文件大900 KB。 使用GeoPandas的大小大约增加了12.5%。

    教程入门: (Getting started with the tutorial:)

    GitHub repo: https://github.com/carnot-technologies/MapVisualizations

    GitHub回购: https : //github.com/carnot-technologies/MapVisualizations

    Relevant notebook: PlotlyChoroplethDemo.ipynb

    相关笔记本: PlotlyChoroplethDemo.ipynb

    View notebook on NBViewer: Click Here

    在NBViewer上查看笔记本: 单击此处

    导入相关软件包: (Importing relevant packages:)

    import numpy as np
    import pandas as pd
    import plotly.express as px
    import json
    import ogr
    # import geopandas as gpd

    As can be seen from the import packages, we will be using plotly.express to create the visualization.


    了解GeoJSON文件: (Understanding the GeoJSON file:)

    Now that we have the GeoJSON file, let’s open it.


    with open('json_files\\India_States_2020_compressed.json') as f:
    India_states = json.load(f)

    You will see that the properties key for each feature holds the name for that feature, which, in our case, are the various states.


    India_states["features"][0]['properties']>> {'dtname': 'North  & Middle Andaman',
    'stcode11': '35',
    'dtcode11': '639',
    'year_stat': '2011_c',
    'Dist_LGD': 632,
    'State_LGD': 35,
    'JID': 178,
    'state_name': 'ANDAMAN & NICOBAR',
    'FID': 0}

    Let us dig deeper into the geometry and have a look at one lat-lon pair:


    India_states["features"][0]['geometry']['coordinates'][0][0][0]>> [93.7, 7.22]

    As you can see, we have coordinates accurate up to 2 decimal places, or about 1.1 km, which is more than sufficient for us.


    加载数据并创建可视化文件: (Loading the data and creating the visualization:)

    We will use the state_dummy_data_no_null.csv file present in the data folder. We will revisit the ‘no-null’ part shortly.

    我们将使用数据文件夹中存在的state_dummy_data_no_null.csv文件。 我们将在短期内重新讨论“无空”部分。

    #Load the csv file and check its contents. 
    #Make sure that there is one entry for each state in the geojson

    df = pd.read_csv('data/state_dummy_data_no_null.csv')

    Now, with plotly express, generating the visualization is boils down to just a couple of lines of code.

    现在,使用plotly express,生成可视化过程可以归结为几行代码。

    max_value = df['count'].max()
    fig = px.choropleth(df, geojson=India_states, locations='st_nm',
    range_color=(0, max_value),
    )fig.update_geos(fitbounds="locations", visible=False)

    Here, we are specifying df as the dataframe of interest. India_states is the GeoJSON file. st_nm column in df is the relevant column containing the names of the states for which we have data. We want the coloring of each shape to happen according to the count column in df, with the range upper-bound at the max value of count Now, in the GeoJSON, the property which contains the names corresponding to the locations field is state_name . Finally the map projection will be mercator . You can get the list of map projections along with their interpretations on Wikipedia.

    在这里,我们将df指定为感兴趣的数据帧。 India_states是GeoJSON文件。 df中的st_nm列是相关列,其中包含我们拥有数据的州的名称。 我们希望根据df中的count列对每种形状进行着色,范围上限在count的最大值处。现在,在GeoJSON中,包含与location字段相对应的名称的属性为state_name 。 最后,地图投影将成为mercator 。 您可以在Wikipedia上获取地图投影列表及其解释。

    Now, we want the visualization to be limited only to the locations of interest, and not span the lat-lon range of the entire world. That is achieved by setting the fitbounds= “locations” in the update_geos method. To get the list of all arguments of the update_geos method, click here. Finally, we set all margins to zero and display our visualization. To get the list of all arguments of the update_layout method, click here. Do explore the different arguments of the update_geos and the update_layout methods. There’s a lot you can do with them. Congratulations on your first interactive visualization. Take your time and play around with it!

    现在,我们希望将可视化仅限于感兴趣的位置,而不要覆盖整个世界的经纬度范围。 这可以通过在update_geos方法中设置fitbounds= “locations”来实现。 要获取update_geos方法的所有参数的列表, 请单击此处 。 最后,我们将所有边距设置为零并显示可视化。 要获取update_layout方法的所有参数的列表, 请单击此处 。 请探索update_geos和update_layout方法的不同参数。 您可以为他们做很多事情。 恭喜您首次互动可视化。 慢慢来玩吧!

    Please note that plotly express is a higher-level library. If you need a lower level library with enhanced control, you can switch to plotly graph objects. See the references for more information.

    请注意,plotly express是更高级别的库。 如果需要具有增强控件的较低级库,则可以切换到可绘制图形对象。 有关更多信息,请参见参考。

    Image for post

    Now, let us visit the no_null part. We have explicitly made sure that data corresponding to each shape in the GeoJSON is present in the CSV. Where there was no data present, we have added a 0 for the count. Why? Because plotly renders only those shapes for which some data is present. Let us plot only the first 25 rows of the dataframe, taking df.head(25) . The resulting visualization looks like this:

    现在,让我们访问no_null部分。 我们已明确确保在CSV中存在与GeoJSON中每个形状相对应的数据。 如果没有数据,我们将计数添加为0。 为什么? 因为plotly仅渲染那些存在某些数据的形状。 让我们仅绘制数据帧的前25行,取为df.head(25) 。 产生的可视化效果如下所示:

    Image for post

    Now, you certainly don’t want this kind of visualization, especially when there is no background to provide context. We will, however, make good use of the null shapes, when we add a background to the visualization using Mapbox. Till then, you better include data for all shapes. To get a list of all the shape names in the GeoJSON, you can learn the following loop:

    现在,您当然不希望这种可视化,尤其是在没有背景可提供上下文的情况下。 但是,当使用Mapbox向可视化添加背景时,我们充分利用null形状。 到那时,您最好包括所有形状的数据。 要获取GeoJSON中所有形状名称的列表,您可以学习以下循环:

    for i in range(0, len(India_states["features"])):

    This will also help you identify any spelling and case differences between the shape names in your data and the shape names in the GeoJSON.


    保存可视化: (Saving the visualization:)

    Once you are ready with your visualization, you can export it as a standalone HTML file, to share with your friends without sharing the source code, or to include in your website.



    You can also push these visualizations to Chart Studio and then get a direct embed link for your blog or website. We’ll discuss that in the Plotly with Mapbox tutorial.

    您还可以将这些可视化效果推送到Chart Studio,然后直接为您的博客或网站嵌入链接。 我们将在Plotly with Mapbox教程中进行讨论。

    何时使用此库: (When to use this library:)

    This library is incredibly powerful. But its power comes at a cost: file size. If you need an interactive visualization, just use this library without a thought. However, if you are going to add the visualization in a PDF report, or in a static presentation, you can still use plotly and download the visualization as a PNG, but it will consume higher resources compared to a library like GeoPandas.

    这个库非常强大。 但是其功能是有代价的:文件大小。 如果您需要交互式的可视化效果,则无需考虑即可使用该库。 但是,如果要在PDF报表或静态演示文稿中添加可视化文件,则仍然可以使用plotly并将可视化文件下载为PNG,但是与GeoPandas之类的库相比,它将消耗更多资源。

    We are trying to fix some broken benches in the Indian agriculture ecosystem through technology, to improve farmers’ income. If you share the same passion join us in the pursuit, or simply drop us a line on report@carnot.co.in

    我们正在尝试通过技术修复印度农业生态系统中一些破烂的长凳 ,以提高农民的收入。 如果您有同样的热情,请加入我们的行列或者直接给我们写信至report@carnot.co.in

    翻译自: https://medium.com/tech-carnot/interactive-map-based-visualization-using-plotly-44e8ad419b97


  • 交互式数据可视化具有以下特点: 它们使您可以通过更改颜色,参数和图与数据进行交互,因此更易于探索。 它们可以轻松,即时地进行操作。 由于您可以与他们互动,因此可以在您面前更改图表。 例如,在本文中,您将...


    静态 vs 交互式



    • 它们使您可以通过更改颜色,参数和图与数据进行交互,因此更易于探索。
    • 它们可以轻松,即时地进行操作。 由于您可以与他们互动,因此可以在您面前更改图表。 例如,在本文中,您将创建一个交互式滑块。 当更改此滑块的位置并且所看到的图形发生变化时,您还可以创建复选框,以选择想要查看的参数。
    • 它们使您能够访问实时数据及其提供的见解。 这样可以快速有效地分析趋势。
    • 它们更容易理解,从而使组织可以做出更好的基于数据的决策。
    • 他们消除了拥有多个用于相同信息的图的需求-一个交互式图能够传达相同的见解。
    • 他们可以让你观察关系。

    让我们从一个示例开始,了解通过交互式可视化可以实现的目标。 让我们考虑一个注册健身房会员的数据集:




    我们从该图上可获得的唯一见解是体重与性别之间的关系 - 去该体育馆的男性顾客体重在62kg至91kg之间,女性顾客体重在57kg至86kg之间,其他顾客的体重在61kg至90kg之间。 但是,数据集中存在用于生成该箱形图的第三个特征-年龄。 在前面的静态图中添加此功能可能会导致在理解数据方面的混乱。 因此,对于使用静态可视化显示所有三个功能之间的关系,我们有些困惑。 通过创建交互式可视化文件,可以轻松解决此问题,如下所示:


    在前面的方框图中,为年龄功能引入了一个滑块。 用户可以手动滑动滑块的位置,以观察体重,性别和年龄在不同年龄值之间的关系。 此外,还有一个悬停工具,允许用户获得有关数据的更多信息。




    上图描述了34岁时的数据–没有男性健身客户; 但是,最重的34岁女性客户体重为100公斤,而最轻的女性客户体重为71公斤。

    但是,区分静态可视化和交互式可视化时还有更多方面要考虑。 让我们看一下下表:


    最终,交互式数据可视化将数据的讨论转变为讲故事的艺术,从而简化了理解数据试图告诉我们的过程。 他们既有益于创建可视化的人(因为他们试图传达的消息和信息被有效且以视觉愉悦的方式传达),也有益于查看可视化的人(因为他们几乎可以立即理解并观察模式和见解) 。 这些方面是将交互式可视化与静态可视化分开的地方。


    正如我们前面提到的,交互式数据可视化的关键方面是它能够立即或在很短的时间内响应和响应人类的输入。 因此,人工输入本身在交互式数据可视化中起着重要作用。 在此,我们将研究一些人工输入,如何将其引入数据可视化中以及它们对数据理解的影响。


    • 滑块:滑块允许用户查看与一定范围内有关的数据。 当用户更改滑块的位置时,绘图实时更改。 这使用户可以实时查看多个图:


    • 悬停:将光标悬停在图的元素上方可以使用户接收到有关数据点的更多信息,而不仅仅是观察图即可看到。 当您希望传达的信息不能适合绘图本身(例如精确值或简短描述)时,这将很有帮助。 让我们看一下一个悬停工具:


    • 缩放:放大和缩小图是许多交互式数据可视化库自己创建的功能。 它们使您可以专注于绘图的特定数据点并仔细查看它们。
    • 可点击参数:可点击参数有多种类型,例如复选框和下拉菜单,它们使用户可以选择要分析和查看的数据的哪些方面。 这里给出一个例子:


    有一些Python库可用于创建这些交互式功能,从而使可视化可以接受人工输入。 因此,在开始编码和创建这些交互式功能之前,让我们快速看一下现有的一些最流行的交互式数据可视化Python库。


    • matplotlib
    • seaborn






    • bokeh
    • plotly








  • 关联知识静态 vs 交互式虽然静态数据可视化是向提取和解释数据集所拥有的价值和信息这一目标迈出的巨大飞跃,但交互性的增加使这些可视化向前迈了一大步。交互式数据可视化具有以下特点:它们使您可以通过更改颜色,...
  • 情节挑战 密谋-交互式可视化和仪表板
  • 基于 plotly Dash 的 GnuCash 数据交互式可视化。 目前处于 pre-alpha 状态,但已经可用。 特征 读取 gnucash XML 文件 自动从事务创建一个桑基图,有很多配置选项 随着时间的推移可视化资产和费用 安装 你需要 ...
  • 随着信息技术的发展和硬件设备成本的降低,当今的互联网存在海量的数据,想要快速从这些数据中获取更多有效的信息,数据...为了解决这个问题,新型的动态可视化开源模块Plotly应运而生。由于Plotly具有动态、美观...
  • 情节挑战 此回购包含“交互式可视化和仪表板”模块的评估。
  • 在谈到数据可视化的时候,相信大多数的读者会想到“matplotlib”、“pyecharts”等第三方模块,今天小编要介绍的可视化框架叫做“plotly”,通过构建基于HTML的交互式图表...
  • 2.8 交互式可视化 可视化之所以被认为是可交互的,是因为它必须满足两个标准: 人为输入:某些信息视觉呈现方面的控制必须可为人所用 响应时间:人为的改变必须及时的纳入可视化 当有大量数据进行可视化处理时,...
  • python数据可视化:使用Dash进行交互式可视化

    万次阅读 多人点赞 2019-01-04 15:32:36
    上一篇介绍的是Bokeh,是一个交互式的可视化工具,Dash同样也是一个优秀的交互式可视化工具,基于plotly,个人感觉Dash比Bokeh更好用,下面是我用Dash写的一个分析报告: 链接在这,感兴趣可以看一下,就是加载需要...
  • 要想做到可交互、多图集成显示,dash是一个不错的选择,但是我这回不用dash,我这回用plotly的js,不过我么有js不是很溜,也是慢慢摸索。。 主要策略就是,在网页通过js做可视化,search获得代码,mysql中查找处理...
  • Python第三方库中我们最常用的可视化库是 pandas,matplotlib,pyecharts, 当然还有 Tableau,另外最近在学习过程中发现另一款可视化神器-Plotly,它是一款用来做数据分析和可视化的在线平台,功能非常强大, 可以...
  • 在此作业中,我建立了一个交互式仪表板,以探索,该目录对定居于人脐的微生物进行了分类。 结果由受试者ID给出,数据集揭示了70%以上的人中存在少量的微生物物种(在研究中也称为操作生物分类单位或OTU)。 访问...
  • 这里想结合mysql 、flask、plotly做一个在网页上展示的股票k线图,而且具有查找的更能,键入股票代码出现该股票的K线图。 使用Plotly 画股票k线图 plotly有集成的k线图方法,使用起来很方便: 这里随机选取一只...
  • 简介本文包含了一些较为流行的工具以及简介,安装方法(基于Linux系统,在一般情况下也适用于其他...1.matplotlibMatplotlib是一个Python 2维绘图库,已经成为python中公认的数据可视化工具,通过Matplotlib你可以很...
  • 2015刚刚过去,我们决定把2015年最出色的10张Plotly...原图都是交互式图片,在这里展示的只是截图。点击文末“阅读原文”,登录网站。 10.“2001-2014,同性婚姻支持倾向” 这些Tufte波形图是由Pew Research制作的...
  • 基于Web浏览器呈现的交互式可视化 多种语言支持Python, Scala, Julia,和R. Json作为BokehJS的输入 HTML作为BokehJS的输出 OFFICIAL: https://docs.bokeh.org https://github.com/bokeh/bokeh Tutori
  • 作为一个数据可视化的研究者,我想要介绍所有那些在数据可视化领域涌现的绝妙技术。因此,我的课程的其中一部分将会是基于研究论文,在线可视化和d3示例的讲座。Python中的数据可视化现在大部分的数据可视化研究...
  • Swift交互式图表库基于。 将专业图形带入了新生的。 图表可以在Jupyter笔记本中查看,也可以作为独立HTML文件查看。 代码库没有外部依赖关系,可以在复杂的调试会话中间轻松地用于可视化数据。 例 下面的代码创建...
  • 这里的逻辑是,根据search获得的股票代码,找到相应的股票名称,进而找到股票的table,然后将其写入pandas.Dataframe 中然后使用 plotly可视化,将可视化文件存储为stock.html,网页加载。。 这里改写了一下之前...



1 2 3 4 5 ... 20
收藏数 2,424
精华内容 969