René's URL Explorer Experiment


Title: [ENH] Support for Multi-Color Line Legends in Plots · Issue #28304 · matplotlib/matplotlib · GitHub

Open Graph Title: [ENH] Support for Multi-Color Line Legends in Plots · Issue #28304 · matplotlib/matplotlib

X Title: [ENH] Support for Multi-Color Line Legends in Plots · Issue #28304 · matplotlib/matplotlib

Description: Need This enhancement proposes adding native support for multi-color lines in the legend of line (and other styles!) plots in Matplotlib. This feature will allow users to represent data series with gradients or multiple colors more intui...

Open Graph Description: Need This enhancement proposes adding native support for multi-color lines in the legend of line (and other styles!) plots in Matplotlib. This feature will allow users to represent data series with...

X Description: Need This enhancement proposes adding native support for multi-color lines in the legend of line (and other styles!) plots in Matplotlib. This feature will allow users to represent data series with...

Opengraph URL: https://github.com/matplotlib/matplotlib/issues/28304

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"[ENH] Support for Multi-Color Line Legends in Plots","articleBody":"### Need\n\nThis enhancement proposes adding native support for multi-color lines in the legend of line (and other styles!) plots in Matplotlib. This feature will allow users to represent data series with gradients or multiple colors more intuitively within the plot legends.\r\n\n\n### Proposed solution\n\nHello, awesome matplotlib people!\r\n\r\n### Why This Enhancement is Needed\r\n\r\n- Improved Data Visualization: Multi-color lines in legends can significantly enhance the readability and interpretability of plots, especially in cases where data series represent a range of values or a transition over time.\r\n- Consistency: Currently, users need to implement custom handlers for multi-color lines, which can be cumbersome and inconsistent. Native support will standardize the implementation.\r\n- User Demand: As data visualizations become more complex and integral to analysis, the demand for more advanced and intuitive plotting features increases. This feature aligns with modern data visualization needs.\r\n\r\n### Benefits\r\n\r\n- Enhanced Clarity: Users can visually match plot lines with legend entries more easily when colors in the legend reflect the actual colors used in the plot.\r\n- Time-Saving: Eliminates the need for users to write and maintain custom legend handlers for multi-color lines.\r\n- Professional Presentation: Provides a more polished and professional look to data visualizations, which is crucial for presentations and publications.\r\n\r\n\r\n## Proposed Implementation\r\nAdd support in the Legend class for a new handler that can process and display multi-color lines. \r\nThis handler will generate a line segment with a gradient or series of colors, consistent with the corresponding plot line.\r\n\r\n###  My current implementation:\r\n```\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom matplotlib.collections import LineCollection\r\nfrom matplotlib.legend_handler import HandlerLineCollection\r\nfrom matplotlib.colors import Normalize\r\nimport cmasher as cmr\r\n\r\nclass HandlerColorLineCollection(HandlerLineCollection):\r\n    def __init__(self, cmap, **kwargs):\r\n        self.cmap = cmap\r\n        super().__init__(**kwargs)\r\n    \r\n    def create_artists(self, legend, artist, xdescent, ydescent, width, height, fontsize, trans):\r\n        x = np.linspace(0, width, self.get_numpoints(legend) + 1)\r\n        y = np.zeros(self.get_numpoints(legend) + 1) + height / 2. - ydescent\r\n        points = np.array([x, y]).T.reshape(-1, 1, 2)\r\n        segments = np.concatenate([points[:-1], points[1:]], axis=1)\r\n        lc = LineCollection(segments, cmap=self.cmap, transform=trans)\r\n        lc.set_array(x)\r\n        lc.set_linewidth(artist.get_linewidth())\r\n        return [lc]\r\n\r\ndef add_normalized_line_collection(ax, cmap, linewidth=3, linestyle='-'):\r\n    norm = Normalize(vmin=0., vmax=1.)\r\n    t = np.linspace(0, 1, 100)  # Smooth gradient\r\n    lc = LineCollection([np.column_stack([t, t * 0])], cmap=cmap, norm=norm, linewidth=linewidth, linestyle=linestyle)\r\n    lc.set_array(np.linspace(0., 1, len(t)))  # Ensure this spans 0 to 1 for correct normalization\r\n    ax.add_collection(lc)  # Add the LineCollection to the axis\r\n    return lc\r\n\r\n# Sample data\r\nx_data = np.logspace(1, 3, 50)\r\ny_data = np.random.rand(3, len(x_data))\r\n\r\nfig, ax = plt.subplots(figsize=(8, 6))\r\n\r\ncolors = cmr.take_cmap_colors('cmr.rainforest', 3, cmap_range=(0.15, 0.85), return_fmt='hex')\r\nfor i in range(y_data.shape[0]):\r\n    ax.plot(x_data, y_data[i], color=colors[i], lw=3)\r\n    \r\n    ax.set_xlabel('$x$', fontsize=18)\r\n    ax.set_ylabel('$y$', fontsize=18)\r\n\r\n# Create color lines for legend\r\ncolor_line = add_normalized_line_collection(ax, cmap=\"cmr.rainforest\", linewidth=4)\r\n\r\n# Existing legend handles and labels\r\nhandles, labels = ax.get_legend_handles_labels()\r\nhandles.append(color_line)\r\nlabels.append(\"Colormap-based Line\")\r\n\r\nax.legend(handles, labels, handler_map={color_line: HandlerColorLineCollection(cmap=\"cmr.rainforest\", numpoints=30)}, loc=\"upper right\", frameon=True, fontsize=15)\r\n\r\nplt.show()\r\n\r\n```\r\n\r\n\u003cimg width=\"710\" alt=\"Screenshot 2024-05-26 at 17 40 26\" src=\"https://github.com/matplotlib/matplotlib/assets/32773944/61066b2b-418f-4daf-8326-359b494a021a\"\u003e\r\n\r\n\r\n### Proposed usage\r\n```\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport cmasher as cmr\r\n\r\n# Sample data\r\nx_data = np.logspace(1, 3, 50)\r\ny_data = np.random.rand(3, len(x_data))\r\n\r\nfig, ax = plt.subplots(figsize=(8, 6))\r\n\r\ncolors = cmr.take_cmap_colors('cmr.rainforest', 3, cmap_range=(0.15, 0.85), return_fmt='hex')\r\nfor i in range(y_data.shape[0]):\r\n    ax.plot(x_data, y_data[i], color=colors[i], lw=3)\r\n    \r\n    ax.set_xlabel('$x$', fontsize=18)\r\n    ax.set_ylabel('$y$', fontsize=18)\r\n\r\n# New API for colormap-based lines in legend\r\nax.legend(use_colormap=True, loc=\"upper right\", frameon=True, fontsize=15, new_arg='cmr.rainforest', )\r\n\r\nplt.show()\r\n\r\n```\r\n\r\nPlease note that it would be beneficial to allow passing either a colormap or a list of colors (in HEX) to this new argument (new_arg) in the legend. Ideally, the legend object should be able to internally determine the colors used in the plot lines, making the process seamless and intuitive for the user.\r\n\r\nI am also [including a version](https://gist.github.com/JBorrow/4d1fed2abf275b9f7a4140f0099fd0b0) from a colleague.\r\n\r\n\r\nMany thanks!\r\nNiko\r\n","author":{"url":"https://github.com/nikosarcevic","@type":"Person","name":"nikosarcevic"},"datePublished":"2024-05-26T16:46:01.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":19},"url":"https://github.com/28304/matplotlib/issues/28304"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:298cb07b-790f-d824-3085-5e3004e8fb07
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idCD26:153E3D:D93845:1286A12:6A5215F6
html-safe-nonce1a7a6eb289d3d6c1c11bdbb1c78eb72eda2351426a6cd95863af2782ba65ce92
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDRDI2OjE1M0UzRDpEOTM4NDU6MTI4NkExMjo2QTUyMTVGNiIsInZpc2l0b3JfaWQiOiI0NDcyODk2MzYzOTQ5MDY5ODE0IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0=
visitor-hmacd4b4adc4dbd6f2fa629feccdc6d716776c41f5bc235c3059e7f497f6f88943f2
hovercard-subject-tagissue:2317842180
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/matplotlib/matplotlib/28304/issue_layout
twitter:imagehttps://opengraph.githubassets.com/94673db84078a1e4894a306deef029a8d24315b742e908d272e07d1ef2f5b30d/matplotlib/matplotlib/issues/28304
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/94673db84078a1e4894a306deef029a8d24315b742e908d272e07d1ef2f5b30d/matplotlib/matplotlib/issues/28304
og:image:altNeed This enhancement proposes adding native support for multi-color lines in the legend of line (and other styles!) plots in Matplotlib. This feature will allow users to represent data series with...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamenikosarcevic
hostnamegithub.com
expected-hostnamegithub.com
Noneb9a586c06a05a7a86fc7e3f4dbd03e42f6869085879aa184aa6369456dbd50fb
turbo-cache-controlno-preview
go-importgithub.com/matplotlib/matplotlib git https://github.com/matplotlib/matplotlib.git
octolytics-dimension-user_id215947
octolytics-dimension-user_loginmatplotlib
octolytics-dimension-repository_id1385122
octolytics-dimension-repository_nwomatplotlib/matplotlib
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id1385122
octolytics-dimension-repository_network_root_nwomatplotlib/matplotlib
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release7aed05249554b889eb33d002851a973eebcc7e91
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/matplotlib/matplotlib/issues/28304#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmatplotlib%2Fmatplotlib%2Fissues%2F28304
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/open-source/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/open-source/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmatplotlib%2Fmatplotlib%2Fissues%2F28304
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=matplotlib%2Fmatplotlib
Reloadhttps://github.com/matplotlib/matplotlib/issues/28304
Reloadhttps://github.com/matplotlib/matplotlib/issues/28304
Reloadhttps://github.com/matplotlib/matplotlib/issues/28304
Please reload this pagehttps://github.com/matplotlib/matplotlib/issues/28304
matplotlib https://github.com/matplotlib
matplotlibhttps://github.com/matplotlib/matplotlib
Please reload this pagehttps://github.com/matplotlib/matplotlib/issues/28304
Notifications https://github.com/login?return_to=%2Fmatplotlib%2Fmatplotlib
Fork 8.4k https://github.com/login?return_to=%2Fmatplotlib%2Fmatplotlib
Star 23k https://github.com/login?return_to=%2Fmatplotlib%2Fmatplotlib
Code https://github.com/matplotlib/matplotlib
Issues 1.1k https://github.com/matplotlib/matplotlib/issues
Pull requests 409 https://github.com/matplotlib/matplotlib/pulls
Actions https://github.com/matplotlib/matplotlib/actions
Projects https://github.com/matplotlib/matplotlib/projects
Wiki https://github.com/matplotlib/matplotlib/wiki
Security and quality 0 https://github.com/matplotlib/matplotlib/security
Insights https://github.com/matplotlib/matplotlib/pulse
Code https://github.com/matplotlib/matplotlib
Issues https://github.com/matplotlib/matplotlib/issues
Pull requests https://github.com/matplotlib/matplotlib/pulls
Actions https://github.com/matplotlib/matplotlib/actions
Projects https://github.com/matplotlib/matplotlib/projects
Wiki https://github.com/matplotlib/matplotlib/wiki
Security and quality https://github.com/matplotlib/matplotlib/security
Insights https://github.com/matplotlib/matplotlib/pulse
[ENH] Support for Multi-Color Line Legends in Plotshttps://github.com/matplotlib/matplotlib/issues/28304#top
New featurehttps://github.com/matplotlib/matplotlib/issues?q=state%3Aopen%20label%3A%22New%20feature%22
status: needs clarificationIssues that need more information to resolve.https://github.com/matplotlib/matplotlib/issues?q=state%3Aopen%20label%3A%22status%3A%20needs%20clarification%22
topic: legendhttps://github.com/matplotlib/matplotlib/issues?q=state%3Aopen%20label%3A%22topic%3A%20legend%22
https://github.com/nikosarcevic
nikosarcevichttps://github.com/nikosarcevic
on May 26, 2024https://github.com/matplotlib/matplotlib/issues/28304#issue-2317842180
https://private-user-images.githubusercontent.com/32773944/333895398-61066b2b-418f-4daf-8326-359b494a021a.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3ODM3NjQ3NzAsIm5iZiI6MTc4Mzc2NDQ3MCwicGF0aCI6Ii8zMjc3Mzk0NC8zMzM4OTUzOTgtNjEwNjZiMmItNDE4Zi00ZGFmLTgzMjYtMzU5YjQ5NGEwMjFhLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNjA3MTElMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjYwNzExVDEwMDc1MFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWRhNjhjMzAxZTgyZDkzMTQxNTk0ZGY4OThjYWViN2ZiOWIyMzdiYzFmYTQ5YmY4OTY2Yjk2Y2FjYjk4NjM1MjcmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JnJlc3BvbnNlLWNvbnRlbnQtdHlwZT1pbWFnZSUyRnBuZyJ9.LOo5MuNbtquY4wY7cMqDg38L0_T_H7eHdSXAEs5Kavc
including a versionhttps://gist.github.com/JBorrow/4d1fed2abf275b9f7a4140f0099fd0b0
New featurehttps://github.com/matplotlib/matplotlib/issues?q=state%3Aopen%20label%3A%22New%20feature%22
status: needs clarificationIssues that need more information to resolve.https://github.com/matplotlib/matplotlib/issues?q=state%3Aopen%20label%3A%22status%3A%20needs%20clarification%22
topic: legendhttps://github.com/matplotlib/matplotlib/issues?q=state%3Aopen%20label%3A%22topic%3A%20legend%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.