Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Pandas
  • Seaborn
  • Matplotlib
  • Altair
  • Bokeh
  • Data Analysis
  • R
  • Machine Learning Math
  • Machin Learning
  • Deep Learning
  • Deep Learning Projects
  • NLP
  • Computer vision
  • Data science
  • Deep learning interview question
  • Machin Learning Interview question
Open In App
Next Article:
Data Visualization using Plotnine and ggplot2 in Python
Next article icon

Plotly for Data Visualization in Python

Last Updated : 19 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Plotly is an open-source Python library designed to create interactive, visually appealing charts and graphs. It helps users to explore data through features like zooming, additional details and clicking for deeper insights. It handles the interactivity with JavaScript behind the scenes so that we can focus on writing Python code to build the charts. In this article, we will see plotting in Plotly and covers how to create basic charts and enhance them with interactive features.

To get started with Plotly simply install it using the following command:

pip install plotly

Understanding Plotly Modules

Plotly consists of two key modules:

  1. plotly.plotly: Used to connect your local machine with Plotly’s server. It provides functions requiring a response from the Plotly server.
  2. plotly.graph_objects: This module is used to define and create plots. It contains objects such as Figure, layout and data, which are responsible for plotting.

Example:

Python
import plotly.express as px

fig = px.line(x=[1, 2], y=[3, 4])

print(fig)

Output:

plotly figure classplotly.tools module contains various tools in the forms of the functions that can increase the Plotly experience. Now let's see how to create some basic charts using plotly.

Basic Charts in Plotly

Here we will see how to generate basic charts using Plotly and apply various customizations to enhance their appearance and functionality. We will learn how to visualize different graph like line charts, scatter plots, bar charts, histograms and pie charts. We will cover the following customizations:

  • Adjusting chart layout
  • Adding annotations
  • Customizing markers and lines

1. Line chart

Plotly line chart is one of the simple plots where a line is drawn to show relation between the X-axis and Y-axis. It can be created using the px.line() method with each data position is represented as a vertex of a polyline mark in 2D space.

Syntax:

plotly.express.line(data_frame=None, x=None, y=None, color=None, title=None)

Parameters:

  • data_frame: Dataset to plot.
  • x: Column name for the X-axis.
  • y: Column name for the Y-axis.
  • color: Color the lines based on this column.
  • title: Title of the plot.

Return: A plotly.graph_objects.Figure object.

Example:

We will be using Iris dataset and it is directly available as part of scikit-learn. df = px.data.iris() from the plotly.express library loads it into a Pandas DataFrame. This dataset contains measurements of sepal length, sepal width, petal length and petal width for 150 iris flowers and categorized into three species: setosa, versicolor and virginica.

Python
import plotly.express as px

df = px.data.iris()

fig = px.line(df, y="sepal_width",)

fig.show()

Output:

line chart plotly

In the above example, we can see that:

  • Plotly automatically assigns labels to the X and Y axes.
  • The data points for both axes are displayed.
  • We can zoom in, zoom out or select specific parts of the data.
  • It provides interactive tools in the top-right corner for chart manipulation.
  • We can also save the chart locally as a static image.

Now let's try to customize our graph a little. 

Example 1: In this example we will use the line dash parameter which is used to group the lines according to the dataframe column passed.

Python
import plotly.express as px

df = px.data.iris()

fig = px.line(df, y="sepal_width", line_group='species')

fig.show()

Output:

line chart plotly with line group

Example 2: In this example, we will group and color the data according to the species. We will also change the line format. For this we will use two attributes such line_dash and color.

Python
import plotly.express as px

df = px.data.iris()

fig = px.line(df, y="sepal_width", line_dash='species',
              color='species')

fig.show()

Output:

plotly line chart with color

2. Bar Chart

A bar chart is a pictorial representation of data that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. These data sets contain the numerical values of variables that represent the length or height. It can be created using the px.bar() method.

Syntax:

plotly.express.bar(data_frame=None, x=None, y=None, color=None, title=None)

Parameters:

  • data_frame: Dataset to plot.
  • x: The column name for the X-axis.
  • y: The column name for the Y-axis.
  • color: Color the bars based on this column.
  • title: Title of the plot.

Return: A plotly.graph_objects.Figure object.

Example:

We will be using tips dataset and df = px.data.tips() from the plotly.express library loads a sample dataset about tips into a Pandas DataFrame. This dataset contains 244 rows and 7 columns with each row representing a single restaurant bill and associated information.

Python
import plotly.express as px

df = px.data.tips()

fig = px.bar(df, x='day', y="total_bill")

fig.show()

Output:

bar chart plotly

Let's try to customize this plot.

Example: Customizations that we will use -

  • color: Used to color the bars.
  • facet_row: Divides the graph into rows according to the data passed
  • facet_col: Divides the graph into columns according to the data passed
Python
import plotly.express as px

df = px.data.tips()

fig = px.bar(df, x='day', y="total_bill", color='sex',
             facet_row='time', facet_col='sex')

fig.show()

Output:

customized bar chart plotly

3. Scatter Plot

A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. A graph in which the values of two variables are plotted along X-axis and Y-axis, the pattern of the resulting points reveals a correlation between them and it can be created using the px.scatter() method.

Syntax:

plotly.express.scatter(data_frame=None, x=None, y=None, color=None, title=None)

Parameters:

  • data_frame: Dataset to plot.
  • x: The column name for the X-axis.
  • y: The column name for the Y-axis.
  • color: Color the bars based on this column.
  • title: Title of the plot.

Return:A plotly.graph_objects.Figure object.

Example:

Python
import plotly.express as px

df = px.data.tips()

fig = px.scatter(df, x='total_bill', y="tip")

fig.show()

Output:

scatter plot plotly

Example: Let's see various customizations available for this chart that we will use - 

  • color: Color the points.
  • symbol: Gives a symbol to each point according to the data passed.
  • size: Size for each point.
Python
import plotly.express as px

df = px.data.tips()

fig = px.scatter(df, x='total_bill', y="tip", color='time',
                 symbol='sex', size='size', facet_row='day',
                 facet_col='time')

fig.show()

Output:

customized scatter plot plotly

4. Histogram

A histogram is used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. It can be created using the px.histogram() method.

Syntax: 

plotly.express.histogram(data_frame=None, x=None, y=None, color=None, nbins=None, histnorm=None, title=None, width=None, height=None)

Parameters:

  • data_frame: Dataset to plot.
  • x: The column name for the X-axis (values to be binned).
  • color: Color the bars based on this column.
  • nbins: Set the number of bins.
  • histnorm: Normalize the histogram (e.g"percent", "density").

Return:A plotly.graph_objects.Figure object.

Example:

Python
import plotly.express as px

df = px.data.tips()

fig = px.histogram(df, x="total_bill")

fig.show()

Output:

histogram plotly

Let's customize the above graph.

Example: Customizations that we will be using are - 

  • color: To color the bars
  • nbins: To set the number of bins
  • histnorm: Mode through which the bins are represented. Different values that can be passed using this argument.
  • barmode: Can be either 'group', 'overlay' or 'relative'.
    1. group: Bars are stacked above zero for positive values and below zero for negative values
    2. overlay: Bars are drawn on the top of each other
    3. group: Bars are placed beside each other.
Python
import plotly.express as px

df = px.data.tips()

fig = px.histogram(df, x="total_bill", color='sex',
                   nbins=50, histnorm='percent',
                   barmode='overlay')

fig.show()

Output:

customized histogram plotly

5. Pie Chart

A pie chart is a circular statistical graphic which is divided into slices to show numerical proportions. It shows a special chart that uses “pie slices” where each sector shows the relative sizes of data. A circular chart cuts in a form of radii into segments to magnitude of different features. It can be created using the px.pie() method.

Syntax:

plotly.express.pie(data_frame=None, names=None, values=None, color=None, hole=None, title=None, width=None, height=None)

Parameters:

  • data_frame: Dataset to plot.
  • names: Column name for the pie chart labels.
  • values: Column name for the size of the slices.
  • hole: Creates a donut chart when set between 0 and 1.

Return: A plotly.graph_objects.Figure object.

Example:

Python
import plotly.express as px

df = px.data.tips()

fig = px.pie(df, values="total_bill", names="day")
fig.show()

Output:

pie plot plotly

Let's customize the above graph.

Example: Customizations that we will be using are:

  • color_discrete_sequence: Strings defining valid CSS colors
  • opacity: It finds how transparent or solid the markers (such as points on a scatter plot) appear. The value should be between 0 and 1
  • hole: Creates a hole in between to make it a donut chart. The value should be between 0 and 1
Python
import plotly.express as px

df = px.data.tips()

fig = px.pie(df, values="total_bill", names="day",
             color_discrete_sequence=px.colors.sequential.RdBu,
             opacity=0.7, hole=0.5)
fig.show()

Output:

customized pir chart plotly

6. Box Plot

A Box Plot is also known as Whisker plot is created to display the summary of the set of data values having properties like minimum, first quartile, median, third quartile and maximum. In the box plot, a box is created from the first quartile to the third quartile, a vertical line is also there which goes through the box at the median. Here x-axis denotes the data to be plotted while the y-axis shows the frequency distribution. It can be created using the px.box() method

Syntax:

plotly.express.box(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, title=None, width=None, height=None)

Parameters:

  • data_frame: Dataset to plot.
  • x: The column name for the X-axis.
  • y: The column name for the Y-axis.
  • color: Color the boxes based on this column.

Return: A plotly.graph_objects.Figure object.

Example:

Python
import plotly.express as px

df = px.data.tips()

fig = px.box(df, x="day", y="tip")

fig.show()

Output:

boxplot plotly

Let's customize the above graph.  

Example: Customizations that we will be using are - 

  • color: used to assign color to marks
  • facet_row: assign marks to facetted subplots in the vertical direction
  • facet_col: assign marks to facetted subplots in the horizontal direction
  • boxmode: One of ‘group’ or ‘overlay’ In ‘overlay’ mode, boxes are on drawn top of one another. In ‘group’ mode, boxes are placed beside each other.
  • notched: If True, boxes are drawn with notches
Python
import plotly.express as px

df = px.data.tips()

fig = px.box(df, x="day", y="tip", color='sex',
             facet_row='time', boxmode='group',
             notched=True)

fig.show()

Output:

styled boxplot plotly

7. Violin Plot

Violin Plot is a method to visualize the distribution of numerical data of different variables. It is similar to Box Plot but with a rotated plot on each side helps in giving more information about the density estimate on the y-axis. The density is mirrored and flipped over and the resulting shape is filled in creating an image resembling a violin. The advantage of a violin plot is that it can show distribution that aren’t shown in a boxplot. On the other hand the boxplot more clearly shows the outliers in the data. It can be created using the px.violin() method.

Syntax:

plotly.express.violin(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, title=None, width=None, height=None)

Parameters:

  • data_frame: Dataset to plot.
  • x: The column name for the X-axis.
  • y: The column name for the Y-axis.
  • color: Color the violins based on this column.

Return: A plotly.graph_objects.Figure object.

Example:

Python
import plotly.express as px

df = px.data.tips()

fig = px.violin(df, x="day", y="tip")

fig.show()

Output:

violin plotl plotly

Let's customize the above graph.  

Example: For customizing the violin plot we will use the same customizations available for the box plot except the boxmode and notched which are not available for the violin plot Setting this parameter to True will show a box plot inside the violin plot.

Python
import plotly.express as px

df = px.data.tips()

fig = px.violin(df, x="day", y="tip", color='sex',
                facet_row='time', box=True)

fig.show()

Output:

styled violin plot pltoly

8. 3D Scatter Plot

3D Scatter Plot shows data points in three dimensions, adding extra information by adjusting color, size and style of the points. These adjustments help make the plot clearer and easier to understand. You can create a 3D scatter plot using the scatter_3d function from the plotly.express class.

Syntax:

plotly.express.scatter_3d(data_frame=None, x=None, y=None, z=None, color=None, symbol=None, size=None, title=None, width=None, height=None)

Parameters:

  • data_frame: Dataset to plot.
  • x: The column name for the X-axis.
  • y: The column name for the Y-axis.
  • z: The column name for the Z-axis.
  • color: Color the points based on this column.
  • size: Size of the points.

Return: A plotly.graph_objects.Figure object.

Example:

Python
import plotly.express as px

df = px.data.tips()

fig = px.scatter_3d(df, x="total_bill", y="sex", z="tip")

fig.show()

Output:

3d scatter plotly

Customizing the 3D scatter plot.

Example: We will use the following customization - 

  • color: Set the color of the markers
  • size: Set the size of the marker
  • symbol: Set the symbol of the plot
Python
import plotly.express as px

df = px.data.tips()

fig = px.scatter_3d(df, x="total_bill", y="sex", z="tip", color='day', 
                    size='total_bill', symbol='time')

fig.show()

Output:

styled 3d scatter plot plotly

Implementing Interactive Features in Plotly

Plotly provides various interactive features which allows users to zoom, hover and click for deeper insights. Beyond these built-in interactions it allows customization with tools like dropdown menus, buttons and sliders. These can be added using the update menu attribute in the plot layout. Let’s explore these features:

1. Dropdown Menu

A drop-down menu allows users to select different options to modify the chart. The update method is used to control the chart based on dropdown choices. In plotly there are 4 possible methods to modify the charts by using update menu method.

  • restyle: modify data or data attributes
  • relayout: modify layout attributes
  • update: modify data and layout attributes
  • animate: start or pause an animation

Example: Here we will be using Tips dataset which contains 244 rows and 7 columns and with each row representing a single restaurant bill and associated information. You can download it from here.

Python
import plotly.graph_objects as px
import numpy as np
import pandas as pd

df = pd.read_csv('/content/tips.csv')

plot = px.Figure(data=[px.Scatter(
    x=df['day'],
    y=df['tip'],
    mode='markers',)
])

plot.update_layout(
    updatemenus=[
        dict(buttons=list([
            dict(
                args=["type", "scatter"],
                label="Scatter Plot",
                method="restyle"
            ),
            dict(
                args=["type", "bar"],
                label="Bar Chart",
                method="restyle"
            )
        ]),
            direction="down",
        ),
    ]
)

plot.show()

Output:

dropdown plotly

2. Adding Buttons

In plotly, adding custom Buttons are used to quickly make actions directly from a record. Custom Buttons can be added to page layouts in CRM, Marketing and Custom Apps. There are also 4 possible methods that can be applied in custom buttons:

  • restyle: modify data or data attributes
  • relayout: modify layout attributes
  • update: modify data and layout attributes
  • animate: start or pause an animation

Example:

Python
import plotly.graph_objects as px
import pandas as pd

df = pd.read_csv('/content/tips.csv')

plot = px.Figure(data=[px.Scatter(
    x=df['day'],
    y=df['tip'],
    mode='markers',)
])

plot.update_layout(
    updatemenus=[
        dict(
            type="buttons",
            direction="left",
            buttons=list([
                dict(
                    args=["type", "scatter"],
                    label="Scatter Plot",
                    method="restyle"
                ),
                dict(
                    args=["type", "bar"],
                    label="Bar Chart",
                    method="restyle"
                )
            ]),
        ),
    ]
)

plot.show()

Output:

button-plotly

3. Creating Sliders and Selectors to the Plot

In Plotly, the range slider is an input control that allows users to select a value range between a specified minimum and maximum. It allows selecting pre-configured ranges and manually inputting minimum and maximum values or dates.

Example:

Python
import plotly.graph_objects as px
import plotly.express as go
import numpy as np

df = go.data.tips()

x = df['total_bill']
y = df['tip']

plot = px.Figure(data=[px.Scatter(
    x=x,
    y=y,
    mode='markers',)
])

plot.update_layout(
    xaxis=dict(
        rangeselector=dict(
            buttons=list([
                dict(count=1,
                    step="day",
                    stepmode="backward"),
            ])
        ),
        rangeslider=dict(
            visible=True
        ),
    )
)

plot.show()

Output:

slider plotly

Building Interactive Dashboards with Plotly Dash

Plotly Dash is a framework for building interactive web applications with Python. It allows us to create dynamic and visually appealing dashboards that can handle complex interactions and data visualizations. In this section, we will see the importance of building interactive dashboards using Plotly Dash.

Steps to Create a Basic Dash App:

1. Install the necessary packages:

!pip install dash

!pip install --upgrade plotly

2. Create and run the Dash app:

Python
import dash
from dash import dcc, html
import plotly.express as px
import pandas as pd

df = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'y': [10, 15, 13, 17, 14]
})

app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Graph(
        id='example-graph',
        figure=px.scatter(df, x='x', y='y', title='Scatter Plot in Dash')
    )
])

if __name__ == '__main__':
    app.run(debug=True, port=8050)

Output:

PLOTLY
Interactive Dashboards

With Plotly we can easily create interactive dashboards that make exploring and understanding data more engaging and insightful.


Next Article
Data Visualization using Plotnine and ggplot2 in Python

N

nikhilaggarwal3
Improve
Article Tags :
  • Data Visualization
  • AI-ML-DS
  • Python-Plotly
  • AI-ML-DS With Python
  • Python Data Visualization

Similar Reads

    Python - Data visualization tutorial
    Data visualization is a crucial aspect of data analysis, helping to transform analyzed data into meaningful insights through graphical representations. This comprehensive tutorial will guide you through the fundamentals of data visualization using Python. We'll explore various libraries, including M
    7 min read
    What is Data Visualization and Why is It Important?
    Data visualization is the graphical representation of information. In this guide we will study what is Data visualization and its importance with use cases.Understanding Data VisualizationData visualization translates complex data sets into visual formats that are easier for the human brain to under
    4 min read
    Data Visualization using Matplotlib in Python
    Matplotlib is a widely-used Python library used for creating static, animated and interactive data visualizations. It is built on the top of NumPy and it can easily handles large datasets for creating various types of plots such as line charts, bar charts, scatter plots, etc. These visualizations he
    10 min read
    Data Visualization with Seaborn - Python
    Seaborn is a widely used Python library used for creating statistical data visualizations. It is built on the top of Matplotlib and designed to work with Pandas, it helps in the process of making complex plots with fewer lines of code. It specializes in visualizing data distributions, relationships
    9 min read
    Data Visualization with Pandas
    Pandas allows to create various graphs directly from your data using built-in functions. This tutorial covers Pandas capabilities for visualizing data with line plots, area charts, bar plots, and more.Introducing Pandas for Data VisualizationPandas is a powerful open-source data analysis and manipul
    5 min read
    Plotly for Data Visualization in Python
    Plotly is an open-source Python library designed to create interactive, visually appealing charts and graphs. It helps users to explore data through features like zooming, additional details and clicking for deeper insights. It handles the interactivity with JavaScript behind the scenes so that we c
    12 min read
    Data Visualization using Plotnine and ggplot2 in Python
    Plotnoine is a Python library that implements a grammar of graphics similar to ggplot2 in R. It allows users to build plots by defining data, aesthetics, and geometric objects. This approach provides a flexible and consistent method for creating a wide range of visualizations. It is built on the con
    7 min read
    Introduction to Altair in Python
    Altair is a statistical visualization library in Python. It is a declarative in nature and is based on Vega and Vega-Lite visualization grammars. It is fast becoming the first choice of people looking for a quick and efficient way to visualize datasets. If you have used imperative visualization libr
    5 min read
    Python - Data visualization using Bokeh
    Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums like notebook, html and server. It is possible to embed bokeh plots in Django and flask apps. Bokeh provides two visualization interfaces to us
    4 min read
    Pygal Introduction
    Python has become one of the most popular programming languages for data science because of its vast collection of libraries. In data science, data visualization plays a crucial role that helps us to make it easier to identify trends, patterns, and outliers in large data sets. Pygal is best suited f
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `${editorValue}`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('.suggest-bottom-btn').css("display","none"); $('#suggestion-section-textarea').hide() $('.thank-you-message').css('display', 'flex'); $('.suggestion-section').css('display', 'none'); jQuery('#suggestion-modal-alert').hide(); }, error:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000."); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences