{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Federico Trotta",
  "title_listed": "Building Interactive Data Visualizations in Python: An Introduction to Plotly",
  "keywords": "Plotly,交互式可视化",
  "domain": "数据处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "部分免费/会员墙",
  "url": "https://towardsdatascience.com/building-interactive-data-visualizations-in-python-an-introduction-to-plotly-3ffdd920fc63/",
  "publish_date": "2023-07",
  "corpus_stage": "预训练/SFT",
  "notes": "",
  "id": "6e958d4d4cda",
  "collected_at": "2026-10-02T00:40:12",
  "title": "Building Interactive Data Visualizations in Python: An Introduction to Plotly | Towards Data Science",
  "body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# Building Interactive Data Visualizations in Python: An Introduction to Plotly\nDiscover the power of interactive visualizations for Data Analysis and Machine Learning\n[Federico Trotta](https://towardsdatascience.com/author/federicotrotta/)\nJuly 19, 20235 min read\n![Image by Gerd Altmann on Pixabay](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1-LbUqAx4xa70Pqg4oyQJUw.jpeg)\nImage by [Gerd Altmann](https://pixabay.com/it/users/geralt-9301/?utm_source=link-attribution&utm_medium=referral&utm_campaign=image&utm_content=1237457) on [Pixabay](https://pixabay.com/it//?utm_source=link-attribution&utm_medium=referral&utm_campaign=image&utm_content=1237457)\nData visualization is one of the most important tasks for Data Professionals. It helps us, in fact, understand the data and to ask more questions for further investigations.\nBut data visualization is not only a task we have to conclude in the Exploratory Data Analysis phase. We may also need to present the data, often to an audience to help it grab some conclusions.\nIn Python, we generally use `matplotlib` and `seaborn` as libraries to plot our graphs.\nHowever, sometimes we may need some interactive visualizations. In some cases, for a better understanding of the data. In some other cases, just to better present our solutions.\nIn this article, we'll talk about `plotly` which is a Python library for making interactive visualizations.\n* * *\nLearn this step by step with the interactive [AI Engineer](https://roadmap.sh/ai-engineer), [AI and Data Scientist](https://roadmap.sh/ai-data-scientist), [Computer Science](https://roadmap.sh/computer-science) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n## What is Plotly?\nAs we can read [on their website](https://plotly.com/python/):\n> Plotly's Python graphing library makes interactive, publication-quality graphs. Examples of how to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, polar charts, and bubble charts.\n> Plotly.py is [free and open source](https://plotly.com/python/is-plotly-free) and you can [view the source, report issues or contribute on GitHub](https://github.com/plotly/plotly.py).\nSo, Plotly is a free and open-source Python library for making interactive visualizations.\nAs we can see on their website, it gives us the possibility to create plots for different scopes: AI/ML, statistical, scientific, financial, and much more.\nSince we're interested in Machine Learning and Data Science, we'll show some plots related to this field and how to create them in Python.\nFinally, to install it, we have to type:\ntext\n\n```\n$ pip install plotly\n```\n\n* * *\n## 1. Interactive Bubble charts\nOne interesting and useful feature of Plotly we can use is the possibility of interactive bubble plots.\nIn the case of bubble charts, in fact, sometimes the bubbles can intersect, making it difficult to read the data. If the graph is interactive, instead, we can read the data more easily.\nLet's see an example:\npython\n\n```\nimport plotly.express as px\nimport pandas as pd\nimport numpy as np\n\n# Generate random data\nnp.random.seed(42)\nn = 50\nx = np.random.rand(n)\ny = np.random.rand(n)\nz = np.random.rand(n) * 100  # Third variable for bubble size\n\n# Create a DataFrame\ndata = pd.DataFrame({'X': x, 'Y': y, 'Z': z})\n\n# Create the scatter plot with bubble size with Plotly\nfig = px.scatter(data, x='X', y='Y', size='Z',\n      title='Interactive Scatter Plot with Bubble Plot')\n\n# Add labels to the bubbles\nfig.update_traces(textposition='top center', textfont=dict(size=11))\n\n# Update layout properties\nfig.update_layout(\n    xaxis_title='X-axis',\n    yaxis_title='Y-axis',\n    showlegend=False\n)\n\n# Display the interactive plot\nfig.show()\n```\n\nAnd we get:\n![The interactive bubble chart we&#039;ve coded. Image by Federico Trotta.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1E2voEmA614dZUm4AIkI0FA.gif)\nThe interactive bubble chart we've coded. Image by Federico Trotta.\nSo, we've created some data with `NumPy` and stored them in a `Pandas` data frame. Then, we've created the interactive plot with the method `px.scatter()` retrieving the data from the data frame, and specifying the title (as opposed to `Matplotlib` in which we insert the title outside the method used to create the plot itself).\n## 2. Interactive correlation matrices\nOne of the tasks I sometimes struggle with is a proper visualization of correlation matrices. These, in fact, can sometimes be challenging to read and visualize when we have a lot of data.\nOne way to solve the problem is to use Plotly to create an interactive visualization.\nFor the scope, let's create a Pandas data frame with 10 columns and create an interactive correlation matrix with Plotly:\npython\n\n```\nimport pandas as pd\nimport numpy as np\nimport plotly.figure_factory as ff\n\n# Create random data\nnp.random.seed(42)\ndata = np.random.rand(100, 10)\n\n# Create DataFrame\ncolumns = ['Column' + str(i+1) for i in range(10)]\ndf = pd.DataFrame(data, columns=columns)\n\n# Round values to 2 decimals\ncorrelation_matrix = df.corr().round(2)  \n\n# Create interactive correlation matrix with Plotly\nfigure = ff.create_annotated_heatmap(\n    z=correlation_matrix.values,\n    x=list(correlation_matrix.columns),\n    y=list(correlation_matrix.index),\n    colorscale='Viridis',\n    showscale=True\n)\n\n# Set axis labels\nfigure.update_layout(\n    title='Correlation Matrix',\n    xaxis=dict(title='Columns'),\n    yaxis=dict(title='Columns')\n)\n\n# Display the interactive correlation matrix\nfigure.show()\n```\n\nAnd we get:\n![The interactive correlation matrix we created. Image by Federico Trotta.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1_sEvH3UryBfS5WxDHi7pJQ.gif)\nThe interactive correlation matrix we created. Image by Federico Trotta.\nSo, in a very simple way, we can create an interactive correlation matrix with the method `ff.create_annotated_map()`.\n## 3. Interactive ML plots\nIn Machine Learning, we sometimes need to compare quantities graphically. And, in these cases, sometimes it's hard to read our plots.\nThe typical case is a ROC/AUC curve where we compare the performance of different ML models. Sometimes, in fact, the curves intercepts and we're not able to properly visualize them.\nTo improve our visualizations, we can use Plotly to create a ROC/AUC curve like so:\npython\n\n```\nimport pandas as pd\nimport numpy as np\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import roc_curve, auc\nimport plotly.graph_objects as go\n\n# Create synthetic binary classification data\nX, y = make_classification(n_samples=1000, n_features=20, random_state=42)\n\n# Scale the data using StandardScaler\nscaler = StandardScaler()\nX_scaled = scaler.fit_transform(X)\n\n# Split the data into train and test sets\nX_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)\n\n# Initialize the models\nknn = KNeighborsClassifier()\nrf = RandomForestClassifier()\ndt = DecisionTreeClassifier()\nsvm = SVC(probability=True)\n\n# Fit the models on the train set\nknn.fit(X_train, y_train)\nrf.fit(X_train, y_train)\ndt.fit(X_train, y_train)\nsvm.fit(X_train, y_train)\n\n# Predict probabilities on the test set\nknn_probs = knn.predict_proba(X_test)[:, 1]\nrf_probs = rf.predict_proba(X_test)[:, 1]\ndt_probs = dt.predict_proba(X_test)[:, 1]\nsvm_probs = svm.predict_proba(X_test)[:, 1]\n\n# Calculate the false positive rate (FPR) and true positive rate (TPR) for ROC curve\nknn_fpr, knn_tpr, _ = roc_curve(y_test, knn_probs)\nrf_fpr, rf_tpr, _ = roc_curve(y_test, rf_probs)\ndt_fpr, dt_tpr, _ = roc_curve(y_test, dt_probs)\nsvm_fpr, svm_tpr, _ = roc_curve(y_test, svm_probs)\n\n# Calculate the AUC (Area Under the Curve) for ROC curve\nknn_auc = auc(knn_fpr, knn_tpr)\nrf_auc = auc(rf_fpr, rf_tpr)\ndt_auc = auc(dt_fpr, dt_tpr)\nsvm_auc = auc(svm_fpr, svm_tpr)\n\n# Create an interactive AUC/ROC curve using Plotly\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=knn_fpr, y=knn_tpr, name='KNN (AUC = {:.2f})'.format(knn_auc)))\nfig.add_trace(go.Scatter(x=rf_fpr, y=rf_tpr, name='Random Forest (AUC = {:.2f})'.format(rf_auc)))\nfig.add_trace(go.Scatter(x=dt_fpr, y=dt_tpr, name='Decision Tree (AUC = {:.2f})'.format(dt_auc)))\nfig.add_trace(go.Scatter(x=svm_fpr, y=svm_tpr, name='SVM (AUC = {:.2f})'.format(svm_auc)))\nfig.update_layout(title='AUC/ROC Curve',\n                  xaxis=dict(title='False Positive Rate'),\n                  yaxis=dict(title='True Positive Rate'),\n                  legend=dict(x=0.7, y=0.2))\n# Show plot\nfig.show()\n```\n\nAnd we get:\n![The AUC/ROC curve we&#039;ve created. Image by Federico Trotta.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1bQNUbqb_D1sx-IuKo0T6Eg.gif)\nThe AUC/ROC curve we've created. Image by Federico Trotta.\nSo, with the method `add.trace(go.Scatter)` we've created scatterplots for each ML model we've used (KNN, SVM, Decision Tree, and Random Forest).\nThis way, it's easy to display the details and the values of the zones where the curves intercept themselves.\n* * *\n## Conclusions\nIn this article, we've shown a quick introduction to Plotly and we've seen how we can use it for better visualizations in data analysis and Machine Learning.\nAs we can see, this is a low-code library that, indeed, helps us better visualize our data, improving our results.\n* * *\n![Federico Trotta](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1Qgmrx70AYppweXztN8b0VA.png)\nFederico Trotta\nHi, I'm Federico Trotta and I'm a freelance Technical Writer.\nWant to collaborate with me? [Contact me](https://bio.link/federicotrotta).\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657183787_vf5bj8.png)\nWritten By\n## [Federico Trotta](https://towardsdatascience.com/author/federicotrotta/)\n[See all from Federico Trotta](https://towardsdatascience.com/author/federicotrotta/)\n[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Federico Trotta](https://towardsdatascience.com/tag/federico-trotta/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Technology](https://towardsdatascience.com/tag/technology/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fbuilding-interactive-data-visualizations-in-python-an-introduction-to-plotly-3ffdd920fc63%2F&title=Building%20Interactive%20Data%20Visualizations%20in%20Python%3A%20An%20Introduction%20to%20Plotly)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fbuilding-interactive-data-visualizations-in-python-an-introduction-to-plotly-3ffdd920fc63%2F&title=Building%20Interactive%20Data%20Visualizations%20in%20Python%3A%20An%20Introduction%20to%20Plotly)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fbuilding-interactive-data-visualizations-in-python-an-introduction-to-plotly-3ffdd920fc63%2F&text=Building%20Interactive%20Data%20Visualizations%20in%20Python%3A%20An%20Introduction%20to%20Plotly)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/09/18unCBBvDkokiH9jsOY91lg.png)](https://towardsdatascience.com/adapting-data-science-tools-for-social-impact-in-philanthropy-73a8a382c79c/)\n## [Adapting Data Science Tools for Social Impact in Philanthropy](https://towardsdatascience.com/adapting-data-science-tools-for-social-impact-in-philanthropy-73a8a382c79c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nData Science at the Rockefeller Foundation\n[TDS Editors](https://towardsdatascience.com/author/towardsdatascience/)\nSeptember 8, 20219 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/0PsIHby2oXxxBguOt-scaled.jpg)](https://towardsdatascience.com/5-reasons-to-prioritize-your-ai-business-strategy-ff41d0ee2a33/)\n## [5 reasons why companies need to develop and prioritize their AI Business strategies now!](https://towardsdatascience.com/5-reasons-to-prioritize-your-ai-business-strategy-ff41d0ee2a33/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nCompanies need to have an effective AI strategy aligned with business objectives and models to thrive in the digital age.\n[Jair Ribeiro](https://towardsdatascience.com/author/jairribeiro/)\nMay 10, 202111 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/09/0H-qUY4KLpoFCtSA6-scaled.jpg)](https://towardsdatascience.com/evaluation-of-clustering-methods-for-discovering-wind-turbine-neighbors-27849dea14a2/)\n## [Evaluation of Clustering Methods for Discovering Wind Turbine Neighbors](https://towardsdatascience.com/evaluation-of-clustering-methods-for-discovering-wind-turbine-neighbors-27849dea14a2/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nAn application of data science techniques in renewable energy data analysis\n[Abiodun Olaoye](https://towardsdatascience.com/author/aolaoye/)\nSeptember 30, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/03/1I4DLuT89QvOWSDb-SQp8Sw-scaled.jpeg)](https://towardsdatascience.com/natural-language-fundamentals-intro-implementation-of-sentiment-analysis-machine-translation-c79662e52624/)\n## [Natural Language Fundamentals - Intro & Implementation of Sentiment Analysis, Machine Translation...](https://towardsdatascience.com/natural-language-fundamentals-intro-implementation-of-sentiment-analysis-machine-translation-c79662e52624/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nMultilingual language modeling in the Natural Language space.\n[Farzad Nobar](https://towardsdatascience.com/author/fmnobar/)\nMarch 20, 20239 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/07/1Mz2MjFYbzLzElLMr_Cffgg-scaled.jpeg)](https://towardsdatascience.com/visualizing-cannabis-sales-and-cost-ddd35c2402b1/)\n## [Visualizing Cannabis Sales and Cost](https://towardsdatascience.com/visualizing-cannabis-sales-and-cost-ddd35c2402b1/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nConverting administrative reports into meaningful information\n[Brian Perron, PhD](https://towardsdatascience.com/author/b-r-i-a-n/)\nJuly 5, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/15aO3oa3EbUR-1qmNb1Q_dA-scaled.jpeg)](https://towardsdatascience.com/python-vs-r-the-basics-d754c45c1596/)\n## [Python vs R: The Basics](https://towardsdatascience.com/python-vs-r-the-basics-d754c45c1596/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nAn aspiring data scientist's guide on deciding between two popular languages.\n[Sidney Kung](https://towardsdatascience.com/author/sidneykung/)\nOctober 28, 20205 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/0GuJ17oCMYqlyM4eg.jpg)](https://towardsdatascience.com/the-battle-of-interactive-geographic-visualization-part-3-plotly-graph-objects-go-c3d3f2a00132/)\n## [The Battle of Interactive Geographic Visualization Part 3- Plotly Graph Objects (Go)](https://towardsdatascience.com/the-battle-of-interactive-geographic-visualization-part-3-plotly-graph-objects-go-c3d3f2a00132/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nUsing the Best of Plotly's Response to the Growing Demand for Geovisualization\n[TheDataProf](https://towardsdatascience.com/author/francisadrianviernes/)\nDecember 14, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/03/1loC5ZbwHqXVRXJx9CP4DeA.png)](https://towardsdatascience.com/an-ai-powered-analysis-of-our-postal-service-through-tweets-fa1764409905/)\n## [An AI-Powered Analysis of our Postal Service Through Tweets](https://towardsdatascience.com/an-ai-powered-analysis-of-our-postal-service-through-tweets-fa1764409905/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nDelving into Machine Learning, Topic Modeling, and Sentiment Analysis to Uncover Valuable Customer Perspectives\n[John Adeojo](https://towardsdatascience.com/author/johnadeojo/)\nMarch 22, 202313 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/05/1SApqu3BySROEDSuSydVISg-scaled.jpeg)](https://towardsdatascience.com/5-questions-to-consolidate-your-knowledge-of-python-lists-4a63ba1ab05e/)\n## [5 Questions to Consolidate Your Knowledge of Python Lists](https://towardsdatascience.com/5-questions-to-consolidate-your-knowledge-of-python-lists-4a63ba1ab05e/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nPicked from Stackoverflow\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nMay 19, 20225 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3642/image?etag=1780830904480&width=500&height=500) Check Your Biases ](https://towardsdatascience.com/check-your-biases-ba2685a7f799/ \"Check Your Biases\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4973/image?etag=1782232567105&width=500&height=500) Machine Learning Tricks, Learning with ChatGPT, and Other Recent Must-Reads ](https://towardsdatascience.com/machine-learning-tricks-learning-with-chatgpt-and-other-recent-must-reads-f277648a1921/ \"Machine Learning Tricks, Learning with ChatGPT, and Other Recent Must-Reads\")\n\n\nword word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word\n  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1  \nmmMwWLliI0fiflO&1\n",
  "metadata": {
    "title": "Building Interactive Data Visualizations in Python: An Introduction to Plotly | Towards Data Science",
    "description": "Discover the power of interactive visualizations for Data Analysis and Machine Learning",
    "keywords": null,
    "author": "Federico Trotta",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Building Interactive Data Visualizations in Python: An Introduction to Plotly",
    "og:description": "Discover the power of interactive visualizations for Data Analysis and Machine Learning",
    "og:url": "https://towardsdatascience.com/building-interactive-data-visualizations-in-python-an-introduction-to-plotly-3ffdd920fc63/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1-LbUqAx4xa70Pqg4oyQJUw.jpeg",
    "og:image:width": "1280",
    "og:image:height": "853",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Federico Trotta",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "5 min read",
    "article:published_time": "2023-07-19T13:02:36.000Z",
    "article:modified_time": "2023-07-19T13:02:36.000Z",
    "article:author": "https://towardsdatascience.com/author/federicotrotta/"
  },
  "paywall": {
    "listed_paid": true,
    "detected": false,
    "marker": "",
    "public_only": true,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": "",
    "retried": true
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/6e958d4d4cda/code/block_000.txt",
      "chars": 21
    },
    {
      "language": "txt",
      "file": "attachments/6e958d4d4cda/code/block_001.txt",
      "chars": 714
    },
    {
      "language": "txt",
      "file": "attachments/6e958d4d4cda/code/block_002.txt",
      "chars": 779
    },
    {
      "language": "txt",
      "file": "attachments/6e958d4d4cda/code/block_003.txt",
      "chars": 2438
    }
  ],
  "images": [
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1-LbUqAx4xa70Pqg4oyQJUw.jpeg",
      "alt": "Image by Gerd Altmann on Pixabay",
      "local_path": "attachments/6e958d4d4cda/images/000.jpeg",
      "bytes": 74975,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1E2voEmA614dZUm4AIkI0FA.gif",
      "alt": "The interactive bubble chart we&#039;ve coded. Image by Federico Trotta.",
      "local_path": "attachments/6e958d4d4cda/images/001.gif",
      "bytes": 74095,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1_sEvH3UryBfS5WxDHi7pJQ.gif",
      "alt": "The interactive correlation matrix we created. Image by Federico Trotta.",
      "local_path": "attachments/6e958d4d4cda/images/002.gif",
      "bytes": 98671,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1bQNUbqb_D1sx-IuKo0T6Eg.gif",
      "alt": "The AUC/ROC curve we&#039;ve created. Image by Federico Trotta.",
      "local_path": "attachments/6e958d4d4cda/images/003.gif",
      "bytes": 99185,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/1Qgmrx70AYppweXztN8b0VA.png",
      "alt": "Federico Trotta",
      "local_path": "attachments/6e958d4d4cda/images/004.png",
      "bytes": 321502,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/09/18unCBBvDkokiH9jsOY91lg.png",
      "alt": "",
      "local_path": "attachments/6e958d4d4cda/images/005.png",
      "bytes": 1960801,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/0PsIHby2oXxxBguOt-scaled.jpg",
      "alt": "",
      "local_path": "attachments/6e958d4d4cda/images/006.jpg",
      "bytes": 313147,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/09/0H-qUY4KLpoFCtSA6-scaled.jpg",
      "alt": "",
      "local_path": "attachments/6e958d4d4cda/images/007.jpg",
      "bytes": 619532,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/03/1I4DLuT89QvOWSDb-SQp8Sw-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/6e958d4d4cda/images/008.jpeg",
      "bytes": 797924,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/07/1Mz2MjFYbzLzElLMr_Cffgg-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/6e958d4d4cda/images/009.jpeg",
      "bytes": 624202,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/15aO3oa3EbUR-1qmNb1Q_dA-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/6e958d4d4cda/images/010.jpeg",
      "bytes": 251872,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/0GuJ17oCMYqlyM4eg.jpg",
      "alt": "",
      "local_path": "attachments/6e958d4d4cda/images/011.jpg",
      "bytes": 581024,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/03/1loC5ZbwHqXVRXJx9CP4DeA.png",
      "alt": "",
      "local_path": "attachments/6e958d4d4cda/images/012.png",
      "bytes": 1980320,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/05/1SApqu3BySROEDSuSydVISg-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/6e958d4d4cda/images/013.jpeg",
      "bytes": 286071,
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [],
  "links": [],
  "retry_at": "2026-10-03T08:01:22",
  "repair_version": 2,
  "repaired_at": "2026-10-14T11:11:49Z",
  "source_url": "https://towardsdatascience.com/building-interactive-data-visualizations-in-python-an-introduction-to-plotly-3ffdd920fc63/",
  "delivery_status": "excluded_paid",
  "discovery_status": "excluded_paid",
  "missing_reason": "按原约定排除付费/会员全文"
}