Trending March 2024 # How To Add Legends To Charts In Python? # Suggested April 2024 # Top 5 Popular

You are reading the article How To Add Legends To Charts In Python? updated in March 2024 on the website Moimoishop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested April 2024 How To Add Legends To Charts In Python?

Introduction…

The main purpose of charts is to make understand data easily. “A picture is worth a thousand words” means complex ideas that cannot be expressed in words can be conveyed by a single image/chart.

When drawing graphs with lot of information, a legend may be pleasing to display relevant information to improve the understanding of the data presented.

How to do it..

In matplotlib, legends can be presented in multiple ways. Annotations to draw attention to specific points are also useful to help the reader understand the information displayed on the graph.

1. Install matplotlib by opening up the python command prompt and firing pip install matplotlib.

2. Prepare the data to be displayed.

Example import matplotlib.pyplot as plt # data prep (I made up data no accuracy in these stats) mobile = ['Iphone','Galaxy','Pixel'] # Data for the mobile units sold for 4 Quaters in Million units_sold = (('2024',12,8,6), ('2024',14,10,7), ('2024',16,12,8), ('2024',18,14,10), ('2024',20,16,5),)

3. Split the data into arrays for each company company’s mobile units.

Example # data prep - splitting the data IPhone_Sales = [Iphones for Year, Iphones, Galaxy, Pixel in units_sold] Galaxy_Sales = [Galaxy for Year, Iphones, Galaxy, Pixel in units_sold] Pixel_Sales = [Pixel for Year, Iphones, Galaxy, Pixel in units_sold] # data prep - Labels Years = [Year for Year, Iphones, Galaxy,Pixel in units_sold] # set the position Position = list(range(len(units_sold))) # set the width Width = 0.2

4. Creating a Bar graph with the data chúng tôi product sales gets a call to .bar, specifying its position and sales.

Annotation is added using the xy and xytext attributes. Looking at the data, the Google Pixel mobile sales have dropped by 50% i.e. from 10Million units sold in 2023 to just 5Million in 2023. So we are going to set the text and annotation to out last bar.

Finally, we will add the legend using the legend chúng tôi default, matplotlib will draw the legend over an area where there’s the least overlap of data.

Example plt.bar([p - Width for p in Position], IPhone_Sales, width=Width,color='green') plt.bar([p for p in Position], Galaxy_Sales , width=Width,color='blue') plt.bar([p + Width for p in Position], Pixel_Sales, width=Width,color='yellow')

# Set X-axis as years plt.xticks(Position, Years)

# Set the Y axis label plt.xlabel('Yearly Sales') plt.ylabel('Unit Sales In Millions')

# Set the annotation Use the xy and xytext to change the arrow plt.annotate('50% Drop in Sales', xy=(4.2, 5), xytext=(5.0, 12), horizontalalignment='center', arrowprops=dict(facecolor='red', shrink=0.05))

# Set the legent Finally let us save the figure.

import matplotlib.pyplot as plt

# data prep (I made up data no accuracy in these stats) mobile = ['Iphone','Galaxy','Pixel']

# Data for the mobile units sold for 4 Quaters in Million units_sold = (('2024',12,8,6), ('2024',14,10,7), ('2024',16,12,8), ('2024',18,14,10), ('2024',20,16,5),)

# data prep - splitting the data IPhone_Sales = [Iphones for Year, Iphones, Galaxy, Pixel in units_sold] Galaxy_Sales = [Galaxy for Year, Iphones, Galaxy, Pixel in units_sold] Pixel_Sales = [Pixel for Year, Iphones, Galaxy, Pixel in units_sold]

# data prep - Labels Years = [Year for Year, Iphones, Galaxy,Pixel in units_sold]

# set the position Position = list(range(len(units_sold)))

# set the width Width = 0.2

plt.bar([p - Width for p in Position], IPhone_Sales, width=Width,color='green') plt.bar([p for p in Position], Galaxy_Sales , width=Width,color='blue') plt.bar([p + Width for p in Position], Pixel_Sales, width=Width,color='yellow')

# Set X-axis as years plt.xticks(Position, Years)

# Set the Y axis label plt.xlabel('Yearly Sales') plt.ylabel('Unit Sales In Millions')

# Set the annotation Use the xy and xytext to change the arrow plt.annotate('50% Drop in Sales', xy=(4.2, 5), xytext=(5.0, 12), horizontalalignment='center', arrowprops=dict(facecolor='red', shrink=0.05))

# Set the legent plt.legend(mobile, title='Manufacturers')

plt.legend(mobile, title='Manufacturers') plt.subplots_adjust(right=1.2)

# plt.show()

You're reading How To Add Legends To Charts In Python?

Excel Alternatives To Radar Charts

I get the fanfare around infographics. They’re used to make information more appealing, grab attention, awaken interest, lessen boredom and make that information memorable and easier to understand.

However sometimes they don’t deliver on all points and often miss the most important point, which is to quickly and clearly communicate your message.

Just take the graphic below by chúng tôi titled “Rebalance of power”, which I wouldn’t say is strictly an infographic but it’s had a bit of zhushing. To test its effectiveness see how long it takes you to:

compare one region’s results to another

find the region with the lowest unemployment %

compare the shape of each region’s radar charts

Now, my economics training consists of one semester as part of my accounting qualification so perhaps I’m not the target audience for this infographic. That said, if the target audience are economists then I’d have thought they don’t need it all pretty to get the message.

So for the purpose of this post let’s assume that the target audience is your average man on the street because I want to address the use of radar charts in general and look at alternatives for them.

Chart Effectiveness

Before we dive in to critiquing the infographic let’s recap the purpose of a chart, which also applies to an infographic:

The goal with any chart or graph is to clearly and quickly communicate your message.

Testing the info-graphic against that statement, and assuming the target audience is your average Joe Blow, it falls short.

To Map or not to Map

Whenever you’re reporting data by region or country it’s tempting to use a map. However the map in this example, while attention grabbing, is really just a space hogging, fancy legend with no substance or message to deliver.

Off the Radar

The radar charts are the real problem here though.

Radar charts display data in a circular fashion, which is the opposite of the straight line comparisons we’re able to subconsciously perform. This means we have to work hard to make any comparisons and as a result we’re likely to make mistakes in our assumptions.

I could go on scolding radar charts but Stephen Few has already written this paper; “Keep Radar Graphs Below the Radar – Far Below”.

The data consists of multiple measures that require different quantitative scales, which a bar graph cannot accommodate.

The objective of the graph is to assess the symmetry of the values rather than to compare their magnitudes.

The data fits a circular display because it is intuitively circular in nature or by convention.

That said, I still think most of the time you’re better off using charts that allow you to plot data in a linear fashion as this makes it easier for all ability levels to interpret. i.e. not only Economists.

Download

Download the Excel workbook to see close ups of the images below and how I set up the Conditional Formatting and in-cell bar charts.

Enter your email address below to download the sample workbook.

By submitting your email address you agree that we can email you our Excel newsletter.

Please enter a valid email address.

Note: This is a .xlsx file please ensure your browser doesn’t change the file extension on download.

Excel Alternatives to Radar Charts

One option is to use Conditional Formatting Data Bars as shown below:

Boring, I hear you say 🙂 I agree it doesn’t have the same attention grabbing appeal of the infographic but it’s a lot quicker and easier to interpret and your readers will thank you for that.

If you wanted to retain some of the eye catching infographic effect you could do something like this:

But, personally I think grouping the data by region makes comparisons difficult. And if you retain the grouping by measure (see below), then the colour coding makes it look like a Christmas tree and you don’t know where to look first:

Note: the map in this example is a static image. This tutorial does not cover creating choropleth maps in Excel but you can find some choropleth chart templates here.

Moral of the Story

If you want to compare data across multiple criteria and regions then radar charts are not ideal. Better choices are Conditional Formatting Data Bars, bar charts, small multiples and Sparklines.

How To Add Tag Input In Reactjs?

We can add a tag input in NextJS by creating a new component for the input field and using the onChange event to handle the inputted tags. We can also use the state to store the tags and display them as they are inputted. Finally, we can add a button or function to submit the final tag list. Let us first understand what is ReactJS and Tag Input.

ReactJS

React is a JavaScript library for building user interfaces. It makes it easy to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render the right components when your data changes. You can also build encapsulated components that manage their own state, then compose them to make complex UIs.

Both small and large, complicated applications can be created with ReactJS. It offers a basic yet reliable feature set to get a web application off the ground. It is easy to master both contemporary and legacy applications and is a faster method of coding a functionality. React provides high quantity of ready-made components readily available.

Tag Input

A tag input is a UI element that allows users to add tags or keywords to an input field. These tags are often used for categorizing or grouping related items, and can be used for search or filtering purposes.

A tag input typically has an input field where users can type in tags, and a button to add the tags to a list. The tags can then be displayed as individual elements, usually with a close button to allow users to remove tags. Some tag inputs also have autocomplete functionality to suggest existing tags as the user types.

To get started first create a new NextJS app and run it on our dev server like this −

npx create-react-app tag-app cd tag-app npm start Approach

Install the react-tag-input library by running the following command in your terminal −

npm install react-tag-input

Import the library in your component file by adding the following line at the top of the file −

import { TagInput } from 'react-tag-input';

Create a state variable to hold the tags, and initialize it with an empty array −

const [tags, setTags] = useState([]);

Add the TagInput component to your JSX code and pass in the tags state variable and a callback function for handling tag changes −

(Optional) You can also customize the TagInput component by passing in additional props such as placeholders and styling. For example, to change the placeholder text for the input field, you can add the following prop −

Use the tags state variable in your component logic as needed. For example, you can display the tags in a list or use them as input for an API call −

That’s it! You now have a functional tag input in your ReactJS project.

Example import React, { useState } from 'react'; import { render } from 'react-dom'; import { COUNTRIES } from './countries'; import './style.css'; import { WithContext as ReactTags } from 'react-tag-input'; return { id: country, text: country, }; }); const KeyCodes = { comma: 188, enter: 13, }; const [tags, setTags] = React.useState([ { id: 'Thailand', text: 'Thailand' }, { id: 'India', text: 'India' }, { id: 'Vietnam', text: 'Vietnam' }, { id: 'Turkey', text: 'Turkey' }, ]); }; setTags([...tags, tag]); }; const newTags = tags.slice(); newTags.splice(currPos, 1); newTags.splice(newPos, 0, tag); setTags(newTags); }; }; return ( <ReactTags tags={tags} suggestions={suggestions} delimiters={delimiters} handleDelete={handleDelete} handleAddition={handleAddition} handleDrag={handleDrag} inputFieldPosition="bottom" autocomplete editable ); }; Output

How To Add Another Account In Google Meet

The rise and rise of competition in the virtual conferencing sphere has pushed Google to fine-tune its own Meet app. Ever since its release in 2023, Google’s virtual conferencing tool has continually been updated to offer useful features and quality of life improvements. But unlike other apps like Zoom, Google insists on you logging in to an account before using Google Meet. This is an important safety requirement that we don’t think Google will easily compromise.

But what if you’ve already logged in to Google Meet with an account and want to join the meeting with a different account? It’s simple – add another account. Here’s how to add and switch between accounts on the Google Meet app as well as the browser. 

2 Ways to add Another Account in Google Meet

The basic requirement of having logged into an account to access Google Meet provides an extra layer of security to video conferencing. But if you’re already logged in and need to attend the meet with a different account, here’s how to do so:

Method #01: On the Google Meet app

Open the Google Meet app and tap on your profile icon at the top right corner. 

Then tap on Add another account.

Enter your account credentials and hit Next.

Go ahead and confirm any authorizations and agreements that come up. And just like that, your account is now added to Google Meet. 

Method #02: On Google Meet website

Then enter your login credentials and hit Next. 

Once you’re signed in, your account will be added to your list of Google Meet accounts. 

How to switch between accounts on the Google Meet app

Google Meet doesn’t switch you automatically to your newly added account. This has to be done manually. Here’s how you can do so on the app. 

Method #01: Using the down Swipe gesture

Open the Google Meet app. Then simply swipe down on your profile icon at the top right corner to switch to the next account.

Cycle through the accounts with up/down swipes until you get to the account that you want to switch to.

Using the gesture feature is the easiest way to do so, especially if you can tell the accounts by the profile icons alone.

Method #02: Using Profile Pic icon

If you don’t know which account is which, tap on the same Profile icon. 

Then find the one that you want to switch to.

Now you also know which account is linked to which picture icon and can simply swipe down on it to easily switch between accounts in the future. 

How to switch between accounts on Google Meet on website

There are a couple of different ways to switch between Google Meet accounts on the browser as well. 

Method #01: From the profile icon

The new Google Meet account will open in a new tab with an extended URL.

Method #02: Using direct URLs on the website

Another way to switch between your Google accounts is to do so by altering the website’s URL.

When you’re logged in to an account, the website URL will have a number at the end of it which looks something like this:

Depending on how many Google accounts you’re logged into, the number at the end of the URL may be different. Every one of your Google accounts is associated with a number based on the order in which they were added (note: not created). And just by changing the number at the end, you can switch to a different account.

Of course, this convenience is only afforded if you know which account was added when, or the number associated with it. To know this, open your Gmail account and check for the number in the website’s URL. 

That’s your account number. Number 0 means this is your primary account. Number ‘1’ means this is the second account, number ‘2’ third, and so on (thing Whole numbers). 

Once you know your account order, just go to the Google Meet website URL, change the number at the end, and hit Enter to switch to that account. 

If you don’t see any number, just add the following at the end of the chúng tôi URL:

/landing?authuser=(number)

Change “(number)” to reflect the account that you want to switch to.

Do you always remain logged in with all the accounts?

Once the accounts are added, you remain logged into them. Even if you switch away from an account, it remains active in the background and can still be contacted. Just as you receive emails on all your Gmail accounts, so will you be able to receive calls on all your Google Meet accounts as well.

Having an account requirement for Google Meets is Google’s way of keeping it well within the Google Suite environment while also ensuring that the security features (and your privacy) are not compromised. But since most of us already have Google accounts, the account requirement shouldn’t be much of a concern. 

How To Add Recent Posts In WordPress? – Webnots

Content is important for running WordPress blog. However, it is not sufficient to have content without sufficient internal linking on each of your page. The effective way is to manually insert relevant links on the post content and showcase related posts in sidebar or footer area. However, adding a list of recent posts can also be useful in most cases for having a solid internet linking structure. In this article, we will explain various options to insert recent posts in WordPress.

Why to Use Recent Posts?

Here are some of the reasons to insert recent posts in your site:

Adding a list of latest posts in home page help visitors to quickly navigate through your content.

You can insert recent post widget in popular content to promote your latest published articles.

It is also good idea to showcase your latest articles in footer or sidebar area.

Insert Recent Posts in WordPress Site

You have different possibilities in WordPress to showcase your latest posts:

Showcase in widgets area like sidebar or footer using WordPress Recent Posts widget.

Insert in-between post content using Gutenberg Recent Posts block.

Showcase recent posts using third-party plugins.

Let us explain all possibilities in the following sections.

1. Insert Related Posts in Widgets Area

The typical way of using Recent Posts widget in WordPress is to showcase your recent articles in sidebar or footer widget area. You can drag and drop the widget if you are using old Classic Editor and you have a widget block with Gutenberg editor.

Change to Grid or List View and Alignment

Since it is a separate block, it does not have any title. You can add a “Heading” blog to insert a title above the widget and group both blocks to a single block if required.

Add Heading to List

Finally, press the “Update” button to publish your changes. The “Latest Posts” widget will look like below on your site.

Latest Posts Widget in Sidebar

Recent Posts in Classic Editor

The process is same to insert recent posts if you are using Classic Editor. However, the widget name will be different as “Recent Posts” instead of “Latest Posts”.

Recent Posts Widget Inserted

The “Recent Posts” widget will look something like below on your published site.

Recent Posts Widget with Date Using Classic Editor

Note: As you can see, Gutenberg does not provide options to show published date and select the number of posts in the latest posts list. Also, no matter you use Gutenberg or Classic Editor, appearance of the widgets is decided by the theme you use.

2. Insert Latest Posts Widget in Content Area

Though “Recent Posts” with Classic Editor offers additional options, it is not available to insert inside the content area. The only option for you is to use Gutenberg “Latest Posts” widget or go for a third-party plugin.

Insert Latest Posts Block in Content Area

The widget instantly show your recent posts and you can toggle the list or grid view.

Latest Posts Block Options

Customizing Latest Posts Widget Inside Content

Unlike widget block, you can find plenty of options to customize the latest posts widget inside your content. You can find all the available options under “Block” section from the sidebar.

Customization Options Latest Posts Widget

Styles – you have three styles to choose from like default, with dividers or with borders.

Post content settings – you can enable this option and show excerpt with specified length or full post below each title.

Post meta settings – toggle author name and post published date.

Featured image – show or hide featured image for each post. Further you can change the image alignment, link image and select the image size.

Sorting and filtering – select the sorting order, filter based on categories and author. You can also restrict the number of items to appear in the list with desired columns for the grid view.

Advanced – this is a common option available for all Gutenberg block to add custom CSS classes.

Below is an example of the latest posts in list view with custom options:

List View Example

The same widget will appear in the grid view with some modifications like below in two columns:

Grid View Example

Note: WordPress also offers Query Loop and Posts List blocks which are used to create posts page based on categories and tags. However, you can use the block’s filtering options to show single page with certain number of newest posts and create a recent posts widget.

3. Using Third-Party Plugins

Frankly, we do not recommend using third-party plugin for inserting recent posts in WordPress as the default Gutenberg block suffice the purpose. However, there are some additional situations like if you want to include custom post types or include specific pages also in the list. The best option is to install and activate “WP Latest Posts” plugin on your site. This plugin offers large number of options to create a beautiful recent posts block which you can insert anywhere using shortcodes or with a Gutenberg block. Note that you can create multiple blocks for different post types and insert the shortcode in your PHP templates to showcase corresponding articles without mixing categories and post types.

Add New Recent Posts Block

The plugin offers numerous filtering and design options for selecting the content source and theme for your widget. Go through the settings and customize as per your requirements.

Design Your Block

After finishing your setup, save the block to create a shortcode.

Get Block Shortcode

Inserting Recent Posts Block

If you are using Classic Editor, the plugin will add a button with the name “Add Latest Posts” in the interface. For Gutenberg, you can paste the shortcode anywhere inside the content area or use the “WP Latest Posts” block.

Paste Shortcode or Use Block

You will not have any option to customize the widget within the editor as you have already setup everything from the plugin’s settings panel.

Publish your article and see the latest posts block in action like below.

Recent Posts with Plugin

You can also use the shortcode in the widget area or inside your post template to show the widget automatically on all your posts.

Final Words

We recommend using “Latest Posts” block from Gutenberg block editor to create beautiful recent posts widget insider post content area. Though the block do not offer any customization when using in the widget area, most themes use custom CSS to show the widget elegantly. If the default block is not sufficient then you can use the plugin as mentioned above to create recent posts in a carousel view.

How To Add Lifecycle Methods To A Class In Reactjs?

Every component in React has a lifecycle that incorporates several phases. Programmers usually think of this lifecycle as the component’s ‘lifetime’. The components experience the following events: Mounting, Updating, Unmounting, and Error handling. Mounting refers to the procedure of adding nodes and updating requires programmers to alter and change these nodes in the DOM. Unmounting, on the other hand, removes nodes and error handling tracks your code to ensure it works and is bug-free.

These occurrences can be compared to a component’s birth, development, and eventual demise. You can override multiple lifecycle methods in each React lifecycle phase to execute code at particular points in the process. With this in mind, let’s shed some light on how to add the above lifecycle methods to a Class component in ReactJS.

Detailed Insights On React Lifecycle Methods

As you know, mounting, updating, and unmounting are primary React Lifecycle methods. The methods used in each phase make it simpler to carry out common operations on the components. React developers can directly extend from React Component with class-based components to access the methods.

The most popular method for managing lifecycle events needed ES6 class-based components prior to React 16.8. In other words, if our code were already written using functional React components, we would need to rewrite those as classes that extend with React.Component and include a specific render function.

The three most popular lifecycle methods, componentDidMount, componentDidUpdate, and componentWillUnmount, could be accessed only then.

How To Use Local State And Extra Features With Ease?

In order to use local state along with extra features in React, you will first have to convert a functional complement to a class component.

Create a React.Component extending ES6 class of the same name

Add an empty method render().

Place the function’s body in the render() method.

Substitute props in the render() body with this.props

Delete any remaining empty function declarations.

render

(

)

{

return

(

)

;

}

Adding Lifecycle Methods to a Class Component

For applications that incorporate a multitude of components, it’s imperative to free up resources. When the clock is first shown to the DOM, we want to start a timer. The React term for this is “mounting.” Additionally, once the DOM created by the clock is deleted, we want to reset that timer. In React, this is referred to as “unmounting.”

Example

import

react from ‘react’

;

class

Clock

extends

React

.

Component

{

constructor

(

props

)

{

super

(

props

)

;

this

.

state

=

{

date

:

new

Date

(

)

}

;

}

componentDidMount

(

)

{

}

componentWillUnmount

(

)

{

}

render

(

)

{

return

(

)

;

}

}

Output Hello, world! It is 10:27:03 AM.

Successfully rendering the component’s output invokes a particular function. This is the componentDidMount() function. Insert a timer here −

componentDidMount

(

)

{

this

.

timerID

=

setInterval

(

1000

)

;

}

It is further possible to insert more fields manually to the Class component. Programmers usually do this when they need to keep something which wasn’t a part of the data flow. Reg despite ReactJS setting up this.state and this.props by itself. These further possess unique meanings like a timer ID. In the lifecycle function componentWillUnmount(), we shall deactivate the timer −

componentWillUnmount

(

)

{

clearInterval

(

this

.

timerID

)

;

}

The Clock component will execute the tick() method, which we will implement last, once every second. It will employ this. To program updates to the component’s local state, use setState() −

Example

class

Clock

extends

React

.

Component

{

constructor

(

props

)

{

super

(

props

)

;

this

.

state

=

{

date

:

new

Date

(

)

}

;

}

componentDidMount

(

)

{

this

.

timerID

=

setInterval

(

1000

)

;

}

componentWillUnmount

(

)

{

clearInterval

(

this

.

timerID

)

;

}

tick

(

)

{

this

.

setState

(

{

date

:

new

Date

(

)

}

)

;

}

render

(

)

{

return

(

)

;

}

}

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

'root'

)

)

;

Output Hello, world! It is 10:30:12 AM. The clock is now ticking every second. Using State Correctly

You should be aware of three aspects concerning setState().

Do Not Modify State Directly

This won’t re-render a component, for example −

Instead

,

use

setState

(

)

:

Only the constructor is capable of assigning this.state.

State Updates May Be Asynchronous

You shouldn’t use this.props, and this.state’s values to determine the next state because they might be modified asynchronously. For example, the following code won’t be applicable while updating the counter −

this

.

setState

(

{

counter

:

this

.

state

.

counter

+

this

.

props

.

increment

,

}

)

;

Instead, refer to other versions of setState() and utilize the one which accepts functions. This is because a few versions see functions as an object that requires fixing. The previous state will be passed as the first argument to that method, and the props present at the moment the update is applied will be passed as the second argument −

counter

:

state

.

counter

+

props

.

increment

}

)

)

;

Although we used an arrow function in the example above, normal functions also work −

this

.

setState

(

function

(

state

,

props

)

{

return

{

counter

:

state

.

counter

+

props

.

increment

}

;

}

)

;

State Updates are Merged

Your state might include a number of independent variables −

constructor

(

props

)

{

super

(

props

)

;

this

.

state

=

{

posts

:

[

]

,

}

;

}

After that, you may update each one separately using different setState() calls −

componentDidMount

(

)

{

this

.

setState

(

{

posts

:

response

.

posts

}

)

;

}

)

;

this

.

setState

(

{

}

)

;

}

)

;

}

Thus, the state component is often considered local or contained. Other than the component that owns and controls it, no other component has access to it.

Bottom Line

We have discussed everything you need to know to add lifecycle methods correctly to Class Components in React. Many programmers generally encounter several difficulties while doing the same because of the codes and technicality involved. Therefore, make sure to follow the steps correctly and cross-check your codes before running a command.

Update the detailed information about How To Add Legends To Charts In Python? on the Moimoishop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!