### Install and Run Textual Plotext Demo Source: https://context7.com/textualize/textual-plotext/llms.txt Install the textual-plotext library using pip and run the built-in demonstration application to explore various plot types. ```bash # Install the library pip install textual-plotext # Run the built-in demo application python -m textual_plotext ``` -------------------------------- ### Install textual-plotext Source: https://github.com/textualize/textual-plotext/blob/main/README.md Use this command to install the textual-plotext library via pip. ```sh $ pip install textual-plotext ``` -------------------------------- ### Run textual-plotext Demo Source: https://github.com/textualize/textual-plotext/blob/main/README.md Execute this command to run the demo application included with textual-plotext, which showcases various examples. ```sh $ python -m textual_plotext ``` -------------------------------- ### Plotext Log Scale Workaround Example Source: https://github.com/textualize/textual-plotext/blob/main/README.md Shows the workaround for the Plotext log scale issue by resetting the scale to linear. ```python >>> import plotext as plt >>> plt.xscale("log") >>> plt.plot(plt.sin(periods=2, length=10**4)) >>> plt.show() >>> plt.xscale("linear") # Note this here! >>> plt.show() >>> plt.show() etc... ``` -------------------------------- ### Plotext Log Scale Error Example Source: https://github.com/textualize/textual-plotext/blob/main/README.md Demonstrates the error that occurs when repeatedly calling show() with a log scale in Plotext. ```python >>> import plotext as plt >>> plt.xscale("log") >>> plt.plot(plt.sin(periods=2, length=10**4)) >>> plt.show() >>> plt.show() ``` -------------------------------- ### Basic Plotext Scatter Plot Source: https://github.com/textualize/textual-plotext/blob/main/README.md This is a basic scatter plot example using the Plotext library directly. It generates a sinusoidal signal and plots it. ```python import plotext as plt y = plt.sin() # sinusoidal test signal plt.scatter(y) plt.title("Scatter Plot") # to apply a title plt.show() # to finally plot ``` -------------------------------- ### Textual PlotextPlot Scatter App Source: https://github.com/textualize/textual-plotext/blob/main/README.md This example demonstrates how to use the PlotextPlot widget within a Textual application. It mirrors the basic Plotext scatter plot but adapted for Textual. ```python from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class ScatterApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt y = plt.sin() # sinusoidal test signal plt.scatter(y) plt.title("Scatter Plot") # to apply a title if __name__ == "__main__": ScatterApp().run() ``` -------------------------------- ### Create Plots with Multiple Axes using Textual Plotext Source: https://context7.com/textualize/textual-plotext/llms.txt This example demonstrates how to create plots with multiple X and Y axes for comparing data with different scales. Use the xside and yside parameters to specify the axes. ```python from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class MultipleAxesApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt # Plot on lower-left axes plt.plot(plt.sin(), xside="lower", yside="left", label="lower left") # Plot on upper-right axes with different phase plt.plot(plt.sin(2, phase=-1), xside="upper", yside="right", label="upper right") plt.title("Multiple Axes Plot") if __name__ == "__main__": MultipleAxesApp().run() ``` -------------------------------- ### Manage Plot Themes Source: https://context7.com/textualize/textual-plotext/llms.txt Demonstrates automatic theme synchronization with Textual and explicit Plotext theme selection. Use `themes()` to list available themes. Requires importing `App`, `ComposeResult`, `PlotextPlot`, and `themes`. ```python from textual.app import App, ComposeResult from textual_plotext import PlotextPlot, themes class ThemedPlotApp(App[None]): def compose(self) -> ComposeResult: # Create plot with auto theme (syncs with Textual app theme) yield PlotextPlot(id="auto-themed") def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt plt.scatter(plt.sin()) plt.title("Auto-Themed Plot") class ExplicitThemeApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot(id="themed-plot") def on_mount(self) -> None: plot = self.query_one(PlotextPlot) # Set explicit Plotext theme (disables auto-theming) plot.theme = "textual-matrix" # Full RGB theme plt = plot.plt plt.scatter(plt.sin()) plt.title("Matrix Theme Plot") # Available themes include: # Standard: "clear", "dark", "default", "dreamland", "elegant", etc. # Textual RGB: "textual-clear", "textual-dark", "textual-matrix", etc. print(themes()) # Get all available theme names if __name__ == "__main__": ThemedPlotApp().run() ``` -------------------------------- ### Create a Scatter Plot with PlotextPlot Source: https://context7.com/textualize/textual-plotext/llms.txt Demonstrates how to create a basic scatter plot using the PlotextPlot widget in a Textual application. Requires importing PlotextPlot and Textual's App and ComposeResult. ```python from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class ScatterApp(App[None]): """Example Textual application showing a Plotext scatter plot.""" def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt y = plt.sin() # Generate sinusoidal test signal plt.scatter(y) plt.title("Scatter Plot") if __name__ == "__main__": ScatterApp().run() ``` -------------------------------- ### Textual Plotext Log Scale Workaround Source: https://github.com/textualize/textual-plotext/blob/main/README.md Illustrates how to implement the Plotext log scale workaround within a Textual application. ```python _ = self.plt.build() self.plt.xscale("linear") ``` -------------------------------- ### Create a Vertical Bar Chart with PlotextPlot Source: https://context7.com/textualize/textual-plotext/llms.txt Illustrates the creation of a vertical bar chart using pizza preference data within a Textual PlotextPlot widget. Ensure PlotextPlot and Textual App components are imported. ```python from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class BarChartApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt pizzas = ["Sausage", "Pepperoni", "Mushrooms", "Cheese", "Chicken", "Beef"] percentages = [14, 36, 11, 8, 7, 4] # Vertical bar chart plt.bar(pizzas, percentages) plt.title("Most Favored Pizzas in the World") class HorizontalBarApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt pizzas = ["Sausage", "Pepperoni", "Mushrooms", "Cheese", "Chicken", "Beef"] percentages = [14, 36, 11, 8, 7, 4] # Horizontal bar chart plt.bar(pizzas, percentages, orientation="horizontal", width=3/5) plt.title("Most Favored Pizzas in the World") class MultipleBarApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt pizzas = ["Sausage", "Pepperoni", "Mushrooms", "Cheese", "Chicken", "Beef"] male_percentages = [14, 36, 11, 8, 7, 4] female_percentages = [12, 20, 35, 15, 2, 1] # Multiple bar chart comparing data sets plt.multiple_bar(pizzas, [male_percentages, female_percentages]) plt.title("Most Favored Pizzas by Gender") if __name__ == "__main__": BarChartApp().run() ``` -------------------------------- ### Create a Line Plot with PlotextPlot Source: https://context7.com/textualize/textual-plotext/llms.txt Shows how to generate a line plot using sinusoidal data within a Textual application's PlotextPlot widget. Imports are necessary for App and PlotextPlot. ```python from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class LinePlotApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt # Line plot with sinusoidal data plt.plot(plt.sin()) plt.title("Line Plot") class MultipleDataApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt # Multiple data sets with labels plt.plot(plt.sin(), label="plot") plt.scatter(plt.sin(phase=-1), label="scatter") plt.title("Multiple Data Sets") if __name__ == "__main__": LinePlotApp().run() ``` -------------------------------- ### Create Matrix Plot Source: https://context7.com/textualize/textual-plotext/llms.txt Generates a matrix plot that dynamically resizes to fill the available widget space. The matrix values are calculated based on the distance from the center of the widget. ```python import random from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class MatrixPlotApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt plt.title("Matrix Plot") def on_resize(self) -> None: """Regenerate matrix on resize to fill available space.""" plot_widget = self.query_one(PlotextPlot) plt = plot_widget.plt # Create gradient matrix based on widget size width, height = plot_widget.size.width, plot_widget.size.height matrix = [ [(abs(r - height / 2) + abs(c - width / 2)) for c in range(width)] for r in range(height) ] plt.clear_data() plt.matrix_plot(matrix) if __name__ == "__main__": MatrixPlotApp().run() ``` -------------------------------- ### Create Confusion Matrix Source: https://context7.com/textualize/textual-plotext/llms.txt Generates a confusion matrix to visualize classification results. It takes actual and predicted labels, along with a list of possible labels for the classes. ```python import random from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class ConfusionMatrixApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt # Sample classification results actual = [random.randrange(0, 4) for _ in range(300)] predicted = [random.randrange(0, 4) for _ in range(300)] labels = ["Autumn", "Spring", "Summer", "Winter"] plt.cmatrix(actual, predicted, labels=labels) ``` -------------------------------- ### Create Histogram Plot Source: https://context7.com/textualize/textual-plotext/llms.txt Generates a histogram with multiple data distributions using `plt.hist()`. Requires importing `random`, `App`, `ComposeResult`, and `PlotextPlot`. ```python import random from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class HistogramApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt # Generate sample data with different distributions data1 = [random.gauss(0, 1) for _ in range(70000)] data2 = [random.gauss(3, 1) for _ in range(42000)] data3 = [random.gauss(6, 1) for _ in range(28000)] bins = 60 plt.hist(data1, bins, label="mean 0") plt.hist(data2, bins, label="mean 3") plt.hist(data3, bins, label="mean 6") plt.title("Histogram Plot") if __name__ == "__main__": HistogramApp().run() ``` -------------------------------- ### Subclass PlotextPlot for Custom Weather Widget Source: https://context7.com/textualize/textual-plotext/llms.txt Demonstrates subclassing PlotextPlot to create a reusable custom widget for plotting weather data. The `Weather` widget manages its own data, units, and plotting logic, updating dynamically. ```python from dataclasses import dataclass from typing import Any from textual import on, work from textual.app import App, ComposeResult from textual.containers import Grid from textual.message import Message from textual.reactive import var from textual_plotext import PlotextPlot class Weather(PlotextPlot): """Custom widget for plotting weather data.""" marker: var[str] = var("sd") def __init__(self, title: str, **kwargs) -> None: super().__init__(**kwargs) self._title = title self._unit = "Loading..." self._data: list[float] = [] self._time: list[str] = [] def on_mount(self) -> None: self.plt.date_form("Y-m-d H:M") self.plt.title(self._title) self.plt.xlabel("Time") def replot(self) -> None: """Redraw the plot with current data.""" self.plt.clear_data() self.plt.ylabel(self._unit) self.plt.plot(self._time, self._data, marker=self.marker) self.refresh() def update(self, data: dict[str, Any], values: str) -> None: """Update plot with new data from API response.""" self._data = data["hourly"][values] self._time = [m.replace("T", " ") for m in data["hourly"]["time"]] self._unit = data["hourly_units"][values] self.replot() class WeatherDashboard(App[None]): CSS = """ Grid { grid-size: 2; } Weather { padding: 1 2; } """ def compose(self) -> ComposeResult: with Grid(): yield Weather("Temperature", id="temperature") yield Weather("Wind Speed", id="windspeed") yield Weather("Precipitation", id="precipitation") yield Weather("Pressure", id="pressure") if __name__ == "__main__": WeatherDashboard().run() ``` -------------------------------- ### Plot Time Series Data Source: https://context7.com/textualize/textual-plotext/llms.txt Visualizes time series data using Plotext's date formatting and datetime utilities. Configure date format with `plt.date_form()`. Requires importing `datetime`, `timedelta`, `App`, `ComposeResult`, and `PlotextPlot`. ```python from datetime import datetime, timedelta from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class TimeSeriesApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt # Configure date format plt.date_form("Y-m-d H:M") # Generate sample time series data start = datetime(2024, 1, 1) times = [(start + timedelta(hours=i)).strftime("%Y-%m-%d %H:%M") for i in range(168)] # One week of hourly data values = plt.sin(periods=3, length=168) plt.plot(times, values, marker="dot") plt.title("Weekly Temperature Trend") plt.xlabel("Time") plt.ylabel("Temperature °C") if __name__ == "__main__": TimeSeriesApp().run() ``` -------------------------------- ### Stream Data to Plot Source: https://context7.com/textualize/textual-plotext/llms.txt Updates a plot dynamically using Textual's interval system, `clear_data()`, and `refresh()` for real-time visualizations. Requires importing `App`, `ComposeResult`, and `PlotextPlot`. ```python from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class StreamingDataApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: self.frame = 0 plt = self.query_one(PlotextPlot).plt plt.title("Streaming Data") # Update plot every 250ms self.set_interval(0.25, self.update_plot) def update_plot(self) -> None: plot_widget = self.query_one(PlotextPlot) plt = plot_widget.plt # Clear previous data and plot new frame plt.clear_data() plt.scatter(plt.sin(periods=2, length=1000, phase=(2 * self.frame) / 50)) # Refresh the widget to render changes plot_widget.refresh() self.frame += 1 if __name__ == "__main__": StreamingDataApp().run() ``` -------------------------------- ### Add Decorators to Plots with Textual Plotext Source: https://context7.com/textualize/textual-plotext/llms.txt Use this snippet to add reference lines (vertical and horizontal) and text labels to your plots. Ensure PlotextPlot is composed in your app and accessed via query_one. ```python from textual.app import App, ComposeResult from textual_plotext import PlotextPlot class DecoratedPlotApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt plt.scatter(plt.sin()) plt.title("Plot with Decorations") # Add reference lines plt.vline(100, "magenta") # Vertical line at x=100 plt.hline(0.5, "blue+") # Horizontal line at y=0.5 class LabeledBarApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt pizzas = ["Sausage", "Pepperoni", "Mushrooms", "Cheese"] percentages = [14, 36, 11, 8] plt.bar(pizzas, percentages) plt.title("Labeled Bar Plot") # Add text labels above each bar for i, pizza in enumerate(pizzas): plt.text(pizza, x=i+1, y=percentages[i]+1.5, alignment="center", color="red") plt.ylim(0, 40) class ShapePlotApp(App[None]): def compose(self) -> ComposeResult: yield PlotextPlot() def on_mount(self) -> None: plt = self.query_one(PlotextPlot).plt plt.title("Geometric Shapes") plt.polygon() # Default polygon plt.rectangle() # Rectangle plt.polygon(sides=100) # Circle approximation if __name__ == "__main__": DecoratedPlotApp().run() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.