Scatter plot with color label and legend specified by c option

Scatter plot with color label and legend specified by c option

In a scatter plot with color labels and a legend specified by the c option, you can achieve this by using the matplotlib library in Python. Here's an example of how to create such a scatter plot:

import matplotlib.pyplot as plt import numpy as np # Sample data x = np.random.rand(50) y = np.random.rand(50) color_labels = np.random.randint(0, 3, size=50) # Generate color labels (0, 1, or 2) # Map color labels to colors colors = ['red', 'green', 'blue'] color_list = [colors[label] for label in color_labels] # Create scatter plot plt.scatter(x, y, c=color_list, label=color_labels, cmap='viridis') # Add color legend legend_labels = list(set(color_labels)) legend_handles = [plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=colors[label], label=label) for label in legend_labels] plt.legend(handles=legend_handles, title='Color Label') # Set labels and title plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Scatter Plot with Color Label and Legend') # Show the plot plt.show() 

In this example, we generate sample data for the x and y coordinates, as well as color labels (0, 1, or 2). We map these color labels to corresponding colors using a list. Then, we create the scatter plot using the scatter function, specifying the color labels and colors using the c parameter. The cmap parameter is used to specify the color map for the legend.

We create legend handles for each color label using plt.Line2D and display the legend using plt.legend().

Adjust the data and styling to match your specific use case.

Examples

  1. How to Create a Scatter Plot with Color Labels and Legends in Python

    • This query explores creating a scatter plot with color labels and legends, using the c option in Matplotlib.
    # If not already installed !pip install matplotlib pandas 
    import matplotlib.pyplot as plt import numpy as np # Create random data x = np.random.rand(100) y = np.random.rand(100) labels = np.random.choice(["Category 1", "Category 2"], size=100) # Create a scatter plot with color labels specified by `c` plt.scatter(x, y, c=labels, cmap="viridis", label="Category") plt.colorbar(label="Category") plt.title("Scatter Plot with Color Label") plt.show() 
  2. Scatter Plot with Color Label Using Custom Color Mapping

    • This snippet demonstrates creating a scatter plot with color labels using custom color mapping.
    # If not already installed !pip install matplotlib numpy 
    import matplotlib.pyplot as plt import numpy as np # Generate random data x = np.random.rand(100) y = np.random.rand(100) colors = np.random.choice(["red", "green", "blue"], size=100) # Create a scatter plot with custom color mapping scatter = plt.scatter(x, y, c=colors) # Add a custom legend based on unique colors unique_colors = set(colors) legend_labels = [plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=color, label=color) for color in unique_colors] plt.legend(handles=legend_labels, title="Colors") plt.title("Scatter Plot with Custom Color Mapping") plt.show() 
  3. Scatter Plot with Color Labels and DataFrame in Python

    • This snippet demonstrates creating a scatter plot with color labels specified by c from a Pandas DataFrame.
    # If not already installed !pip install pandas matplotlib numpy 
    import pandas as pd import matplotlib.pyplot as plt # Create a DataFrame df = pd.DataFrame({ "x": [1, 2, 3, 4, 5], "y": [5, 4, 3, 2, 1], "category": ["A", "B", "A", "B", "A"] }) # Create a scatter plot with color labels from the DataFrame scatter = plt.scatter(df["x"], df["y"], c=df["category"], cmap="viridis") # Create a legend based on unique categories unique_categories = df["category"].unique() legend_labels = [plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=cmap(i), label=category) for i, category in enumerate(unique_categories)] plt.legend(handles=legend_labels, title="Category") plt.title("Scatter Plot with Color Labels from DataFrame") plt.show() 
  4. Scatter Plot with Color Label and Custom Legend

    • This snippet demonstrates creating a scatter plot with a color label and a custom legend in Python.
    # If not already installed !pip install matplotlib numpy 
    import matplotlib.pyplot as plt import numpy as np # Generate random data x = np.random.rand(100) y = np.random.rand(100) labels = np.random.choice([0, 1], size=100) # Create a scatter plot with color labels cmap = plt.cm.get_cmap("coolwarm") scatter = plt.scatter(x, y, c=labels, cmap=cmap) # Create a custom legend with specific colors legend_labels = [ plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=cmap(0), label='Label 0'), plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=cmap(1), label='Label 1') ] plt.legend(handles=legend_labels, title="Custom Legend") plt.title("Scatter Plot with Custom Legend") plt.show() 
  5. Scatter Plot with Color Label and Numeric Data

    • This snippet demonstrates creating a scatter plot with color labels based on numeric data.
    # If not already installed !pip install matplotlib numpy 
    import matplotlib.pyplot as plt import numpy as np # Generate random data x = np.random.rand(100) y = np.random.rand(100) sizes = np.random.rand(100) * 100 # For size-based differentiation # Create a scatter plot with color labels based on data plt.scatter(x, y, c=sizes, cmap="viridis", s=sizes) plt.colorbar(label="Size") plt.title("Scatter Plot with Color Label Based on Data") plt.show() 
  6. Scatter Plot with Color Label Based on Categorical Data

    • This snippet demonstrates creating a scatter plot with color labels based on categorical data.
    # If not already installed !pip install matplotlib seaborn 
    import seaborn as sns import matplotlib.pyplot as plt # Load a dataset with categorical data iris = sns.load_dataset("iris") # Create a scatter plot with color labels based on species sns.scatterplot(x="sepal_length", y="sepal_width", hue="species", data=iris) plt.title("Scatter Plot with Color Label Based on Categorical Data") plt.show() 
  7. Scatter Plot with Color Label and Conditional Formatting

    • This snippet demonstrates creating a scatter plot with color labels and additional conditional formatting.
    # If not already installed !pip install matplotlib numpy 
    import matplotlib.pyplot as plt import numpy as np # Generate random data x = np.random.rand(100) y = np.random.rand(100) condition = x > 0.5 # Condition for color differentiation # Create a scatter plot with conditional coloring plt.scatter(x, y, c=condition, cmap="coolwarm", label="Conditional Formatting") plt.colorbar(label="Condition") plt.title("Scatter Plot with Conditional Formatting") plt.show() 
  8. Scatter Plot with Color Label and Custom Shapes

    • This snippet demonstrates creating a scatter plot with color labels and custom marker shapes.
    # If not already installed !pip install matplotlib numpy 
    import matplotlib.pyplot as plt import numpy as np # Generate random data x = np.random.rand(100) y = np.random.rand(100) labels = np.random.choice(["A", "B"], size=100) # Create a scatter plot with custom shapes markers = {"A": "o", "B": "s"} # Circle for A, square for B colors = {"A": "blue", "B": "red"} for label in set(labels): plt.scatter(x[labels == label], y[labels == label], c=colors[label], marker=markers[label], label=f"Label {label}") plt.legend(title="Custom Shapes") plt.title("Scatter Plot with Custom Shapes and Color Labels") plt.show() 
  9. Scatter Plot with Color Label Based on Time Series Data

    • This snippet demonstrates creating a scatter plot with color labels based on time series data.
    # If not already installed !pip install matplotlib pandas 
    import pandas as pd import matplotlib.pyplot as plt # Create a DataFrame with time series data df = pd.DataFrame({ "x": pd.date_range("2024-01-01", periods=100, freq="D"), "y": np.random.rand(100), "value": np.random.rand(100) * 100 # Used for color labeling }) # Create a scatter plot with time series index and color label plt.scatter(df["x"], df["y"], c=df["value"], cmap="plasma", label="Value") plt.xlabel("Date") plt.ylabel("Random Value") plt.colorbar(label="Color Label") plt.title("Scatter Plot with Time Series and Color Label") plt.show() 
  10. Scatter Plot with Color Label and Interactive Legend

    • This snippet demonstrates creating a scatter plot with an interactive legend to toggle visibility based on color labels.
    # If not already installed !pip install matplotlib numpy 
    import matplotlib.pyplot as plt import numpy as np # Generate random data x = np.random.rand(100) y = np.random.rand(100) labels = np.random.choice(["Group 1", "Group 2"], size=100) # Create a scatter plot with interactive legend scatter = plt.scatter(x, y, c=labels, cmap="coolwarm") # Create a legend with toggling functionality legend = plt.legend(title="Toggle Legend", scatterpoints=1) # Add interactive functionality to toggle visibility def on_click(event): for legend_handle in legend.get_lines(): if legend_handle.contains(event)[0]: idx = list(legend.get_lines()).index(legend_handle) scatter.set_array(np.where(labels == legend_handle.get_label(), None, scatter.get_array())) plt.draw() legend.figure.canvas.mpl_connect("button_press_event", on_click) plt.title("Scatter Plot with Interactive Legend") plt.show() 

More Tags

jwe facet-wrap propagation tensorflow2.0 stringbuilder itemlistener modalpopup zip android-widget read.table

More Python Questions

More Dog Calculators

More Biology Calculators

More Transportation Calculators

More Biochemistry Calculators