### Quickstart: Plotting Weather Data with DataFrame (Compiler Plugin) Source: https://github.com/kotlin/kandy/blob/main/docs/topics/Overview.md This snippet is a continuation of the DataFrame example, showing the initial setup for plotting with the Kandy compiler plugin enabled. It defines the DataFrame and begins the plotting process. ```kotlin val weatherData = dataFrameOf( "time" to listOf(0, 1, 2, 4, 5, 7, 8, 9), "temperature" to listOf(12.0, 14.2, 15.1, 15.9, 17.9, 15.6, 14.2, 24.3), "humidity" to listOf(0.5, 0.32, 0.11, 0.89, 0.68, 0.57, 0.56, 0.5) ) weatherData.plot { // Begin plotting ``` -------------------------------- ### Quickstart: Plotting Weather Data with Map Source: https://github.com/kotlin/kandy/blob/main/docs/topics/Overview.md A practical example using a Map to create a plot with bars colored by humidity and a distinct line layer. Includes scale definitions for axes and aesthetics, and layout customization. ```kotlin val weatherData = mapOf( "time" to listOf(0, 1, 2, 4, 5, 7, 8, 9), "temperature" to listOf(12.0, 14.2, 15.1, 15.9, 17.9, 15.6, 14.2, 24.3), "humidity" to listOf(0.5, 0.32, 0.11, 0.89, 0.68, 0.57, 0.56, 0.5) ) // Combine data into a map plot(weatherData) { // Begin plotting x("time") // Set x-axis with time data y("temperature") { // Set y-axis with temperature data // Define scale for temperature (y-axis) scale = continuous(0.0..25.5) } bars { // Add a bar layer fillColor("humidity") { // Customizing bar colors based on humidity // Setting the color range scale = continuous(range = Color.YELLOW..Color.RED) } borderLine.width = 0.0 // Define border line width } line { width = 3.0 // Set line width color = Color.hex("#6e5596") // Define line color type = LineType.DOTDASH // Specify the line type } layout { title = "Simple plot with kandy-lets-plot" // Add title // Add caption caption = "See `examples` section for more\n complicated and interesting examples!" size = 700 to 450 // Plot dimension settings } } ``` -------------------------------- ### Quickstart: Plotting Weather Data with DataFrame Source: https://github.com/kotlin/kandy/blob/main/docs/topics/Overview.md A practical example using a DataFrame to create a plot with bars colored by humidity and a distinct line layer. Includes scale definitions for axes and aesthetics, and layout customization. ```kotlin val weatherData = dataFrameOf( "time" to listOf(0, 1, 2, 4, 5, 7, 8, 9), "temperature" to listOf(12.0, 14.2, 15.1, 15.9, 17.9, 15.6, 14.2, 24.3), "humidity" to listOf(0.5, 0.32, 0.11, 0.89, 0.68, 0.57, 0.56, 0.5) ) weatherData.plot { // Begin plotting x(time) // Set x-axis with time data y(temperature) { // Set y-axis with temperature data // Define scale for temperature (y-axis) scale = continuous(0.0..25.5) } bars { // Add a bar layer fillColor(humidity) { // Customizing bar colors based on humidity // Setting the color range scale = continuous(range = Color.YELLOW..Color.RED) } borderLine.width = 0.0 // Define border line width } line { width = 3.0 // Set line width color = Color.hex("#6e5596") // Define line color type = LineType.DOTDASH // Specify the line type } layout { // Set plot layout title = "Simple plot with kandy-lets-plot" // Add title // Add caption caption = "See `examples` section for more\n complicated and interesting examples!" size = 700 to 450 // Plot dimension settings } } ``` -------------------------------- ### Setup and Dataframe Creation Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/guides/export_to_file.ipynb Initializes necessary libraries and creates a sample dataframe for plotting. Ensure 'kandy', 'dataframe', and 'useLatestDescriptors' are imported. ```python %useLatestDescriptors %use kandy %use dataframe import java.io.File ``` ```kotlin // Create random density data val rand = java.util.Random(42) val n = 500 val dataset = dataFrameOf( "rating" to List(n / 2) { rand.nextGaussian() } + List(n / 2) { rand.nextGaussian() * 1.5 + 1.5 }, "cond" to List(n / 2) { "A" } + List(n / 2) { "B" } ) ``` -------------------------------- ### Date and Time Format Examples Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Formatting-Guide.md Demonstrates various date and time formatting directives applied to a sample date and time. ```text %a --> "Tue" %A --> "Tuesday" %b --> "Aug" %B --> "August" %d --> "06" %e --> "6" %j --> "218" %m --> "08" %w --> "2" %y --> "19" %Y --> "2019" %H --> "04" %I --> "04" %l --> "4" %M --> "46" %P --> "am" %p --> "AM" %S --> "35" %Y-%m-%dT%H:%M:%S --> "2019-08-06T04:46:35" %m/%d/%Y --> "08/06/2019" %m-%d-%Y %H:%M --> "08-06-2019 04:46" %d.%m.%y --> "06.08.19" %A, %b %e, %Y --> "Tuesday, Aug 6, 2019" %b %d, %l:%M %p --> "Aug 06, 4:46 AM" %B %Y --> "August 2019" %b %e, %Y --> "Aug 6, 2019" %a, %e %b %Y %H:%M:%S --> "Tue, 6 Aug 2019 04:46:35" %B %e %Y %H:%M %p --> "August 6 2019 04:46 AM" ``` -------------------------------- ### Number Formatting Examples Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Formatting-Guide.md Demonstrates various number formatting specifiers for common numeric types. These examples show how to control alignment, padding, signs, grouping, precision, and output type. ```text 08d --> "00000042" _<8d --> "______42" _=8d --> "___42___" _=+8d --> "+_____42" _^11.0% --> "____42%____" _^11,.0% --> "__42,200%__" +08,d --> "+0,000,042" .1f --> "42.0" +.3f --> "+42.000" b --> "101010" #b --> "0b101010" o --> "52" e --> "4.200000e+1" s --> "42.0000" 020,s --> "000,000,000,042.0000" 020.0% --> "0000000000000004200%" ``` -------------------------------- ### Additional Number Formatting Examples Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Formatting-Guide.md Provides further examples of number formatting with different values and specifiers, illustrating fixed-point, general, and currency formats with grouping and precision. ```text format number result .1f 0.42 "0.4" .3g 0.4449 "0.445" ,.12g -4200000 "-4,200,000" 0,.2f 1234567.449 "1,234,567.45" +$,.2f 1e4 "+$10,000.00" ``` -------------------------------- ### Install Kandy and DataFrame in Kotlin Notebooks (Latest) Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Quick-Start-Guide.md Use these magic commands to fetch the latest versions of Kandy and DataFrame for interactive notebook environments. Ensure you run '%useLatestDescriptors' first. ```kotlin %useLatestDescriptors %use dataframe %use kandy ``` -------------------------------- ### Create a Simple Dataset in Kandy Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Quick-Start-Guide.md Define a dataset as a Map where keys are column names (Strings) and values are lists of equal length. This example includes time, humidity, and flow status. ```kotlin val simpleDataset = mapOf( "time, ms" to listOf(12, 87, 130, 149, 200, 221, 250), "relativeHumidity" to listOf(0.45, 0.3, 0.21, 0.15, 0.22, 0.36, 0.8), "flowOn" to listOf(true, true, false, false, true, false, false), ) ``` -------------------------------- ### Launch Jupyter Notebook Source: https://github.com/kotlin/kandy/blob/main/docs/topics/Kandy-in-Jupyter-Notebook.md Start the Jupyter Notebook server from your terminal. This command opens the Jupyter interface in your web browser. ```bash jupyter notebook ``` ```bash jupyter-notebook ``` -------------------------------- ### Install Jupyter Notebook with Pip Source: https://github.com/kotlin/kandy/blob/main/docs/topics/Kandy-in-Jupyter-Notebook.md Install the Jupyter Notebook application using pip. This is a prerequisite for running notebooks in your environment. ```bash pip install notebook ``` -------------------------------- ### Define Dataset for Tooltip Example Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Tooltips-Guide.md Defines a simple DataFrame to be used in Kandy plotting examples. This is a prerequisite for creating plots with tooltips. ```kotlin val dataset = dataFrameOf("x" to listOf(0.0, 1.0), "y" to listOf(0.0, 1.0)) ``` -------------------------------- ### Install Kandy and DataFrame in Kotlin Notebooks (Specific Versions) Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Quick-Start-Guide.md Integrate specific versions of Kandy and DataFrame into your Kotlin notebook by providing version numbers in the '%use' magic commands. ```kotlin %use dataframe(%dataframe_latest_version%) %use kandy(%kandy_latest_version%, %kandy_latest_version%) ``` -------------------------------- ### Configure Axis Tooltip Background Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Styles-Guide.md This example demonstrates how to control the background of axis tooltips. It shows how to make the tooltip background blank or apply a predefined background style. ```kotlin plotGrid( listOf( pointPlotWithStyle("blank tooltip x-axis") { xAxis.tooltip.background { blank = true } }, pointPlotWithStyle("background tooltip x-axis") { xAxis.tooltip.background(eBackground) } ), nCol = 2 ) ``` -------------------------------- ### Multiple Lines with DataFrame and Compiler Plugin Source: https://github.com/kotlin/kandy/blob/main/docs/topics/samples/line/Several-Lines.md This example utilizes the Kandy compiler plugin for a more concise DataFrame plotting experience. It allows direct referencing of column names without quotes. ```kotlin val months = listOf(1, 2, 3, 4, 5) val salesProducts = listOf(200.0, 220.0, 180.0, 240.0, 210.0) val salesClothes = listOf(150.0, 130.0, 160.0, 140.0, 170.0) val salesElectronics = listOf(300.0, 320.0, 310.0, 330.0, 340.0) val dataset = dataFrameOf( "month" to months + months + months, "sales" to salesProducts + salesClothes + salesElectronics, "category" to List(5) { "Products" } + List(5) { "Clothes" } + List(5) { "Electronics" } ) dataset.groupBy { category }.plot { line { x(month) y(sales) color(category) } } ``` -------------------------------- ### Line Gradient with DataFrame and Compiler Plugin Source: https://github.com/kotlin/kandy/blob/main/docs/topics/samples/line/Line-Gradient.md This example utilizes the Kandy compiler plugin for a more concise DataFrame syntax. It creates a line chart with a color gradient, mapping 'temp' to color. ```kotlin val monthTemp = dataFrameOf("month", "temp")( "January", -5, "February", -3, "March", 2, "April", 10, "May", 16, "June", 20, "July", 22, "August", 21, "September", 15, "October", 9, "November", 3, "December", -2 ) monthTemp.plot { line { x(month) y(temp) { scale = continuous(-10..25) } color(temp) { scale = continuous(Color.BLUE..Color.RED) } width = 3.0 } } ``` -------------------------------- ### Create Sample Dataset Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Scatter-Guide.md Generates a sample dataset with categorical and numerical variables for scatter plot examples. This dataset is used across multiple plotting scenarios. ```kotlin val rand = java.util.Random(123) val n = 20 val dataset = dataFrameOf( "cond" to List(n / 2) { "A" } + List(n / 2) { "B" }, "xvar" to List(n) { i: Int -> i }, "yvar" to List(n) { i: Int -> i + rand.nextGaussian() * 3 } ) val cond = "cond"() val xvar = "xvar"() val yvar = "yvar"() ``` -------------------------------- ### Plotting Water Level Fluctuations with DataFrame and Compiler Plugin Source: https://github.com/kotlin/kandy/blob/main/docs/topics/samples/area/Fixed-Area-Coordinate.md This example demonstrates plotting water level fluctuations using a DataFrame with the Kandy compiler plugin. It defines the data and plot aesthetics, including a fixed area. ```kotlin val reservoirDf = dataFrameOf( "month" to columnOf( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ), "waterLvl" to columnOf(4.5, 4.7, 5.0, 5.5, 6.0, 6.5, 6.7, 6.2, 5.8, 5.3, 4.8, 4.6) ) plot(reservoirDf) { layout { title = "Water Level" subtitle = "Annual Water Level Fluctuations in Reservoir" yAxisLabel = "Month" xAxisLabel = "Water Level (meters)" } x(month) y { axis.limits = 3.0..8.0 } line { y(waterLvl) } area { y.constant(5.0) borderLine.type = LineType.DOTTED alpha = 0.5 fillColor = Color.RED } } ``` -------------------------------- ### Get Lets-Plot Information Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/geom_violin.ipynb Retrieves and displays information about the Lets-Plot API and its frontend version. This is useful for verifying the Lets-Plot setup. ```python LetsPlot.getInfo() ``` -------------------------------- ### Histogram with DataFrame and Compiler Plugin Source: https://github.com/kotlin/kandy/blob/main/docs/topics/samples/histogram/Histogram-Settings.md Utilize the Kandy compiler plugin for a more concise DataFrame plotting experience. This example demonstrates plotting a histogram using a column reference directly, alongside standard aesthetic customizations. ```Kotlin val experimentalData = dataFrameOf( "length" to columnOf( 5.92, 6.44, 5.87, 4.99, 5.23, 5.67, 4.89, 5.34, 5.78, 5.12, 5.56, 5.23, 5.78, 6.01, 5.56, 5.67, 5.89, 5.45, 6.12, 5.78, 6.34, 5.67, 6.45, 5.34, 5.89, 6.01, 5.78, 5.23, 5.67, 6.12, 6.23, 5.45, 5.56, 5.67, 5.78, 5.56, 6.23, 5.78, 6.34, 6.12, 5.89, 6.45, 5.78, 6.34, 5.67, 6.56, 5.45, 5.78, 5.89, 6.12, 4.67, 4.79, 5.14, 5.28, 5.22, ) ) experimentalData.plot { histogram(length, binsOption = BinsOption.byNumber(12)) { width = 0.8 alpha = 0.9 fillColor = Color.RED borderLine { color = Color.GREEN width = 0.5 } x.axis.name = "length" } layout.title = "Flight length experiment" } ``` -------------------------------- ### Load MPG Dataset Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/coord_flip.ipynb Loads the MPG dataset from a CSV file into a DataFrame and displays the first few rows. This is a common setup for plotting examples. ```python %useLatestDescriptors //%use dataframe %use ggdsl(0.2.4-dev-5) ``` ```python var mpg = DataFrame.readCsv("https://raw.githubusercontent.com/JetBrains/lets-plot-kotlin/master/docs/examples/data/mpg.csv") mpg.head(3) ``` -------------------------------- ### Line Chart with Reversed Y-Axis using DataFrame and Compiler Plugin Source: https://github.com/kotlin/kandy/blob/main/docs/topics/samples/line/Line-with-Reversed-Axis.md This example demonstrates creating a line chart with a reversed y-axis using a DataFrame and the Kandy compiler plugin. It offers a concise way to define data columns. ```Kotlin val dataset = dataFrameOf( "product" to ('A'..'F').map { it.toString() }.toColumn(), "rating" to columnOf(10, 7, 3, 5, 2, 1) ) plot(dataset) { line { x(rating) { scale = continuous(min = 0, max = 12) } y(product) { scale = continuous(transform = Transformation.REVERSE) } color = Color.RED alpha = 0.85 } } ``` -------------------------------- ### Initialize Lets-Plot Environment Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/qq_plots.ipynb Sets up the Lets-Plot environment with necessary descriptors and libraries. This is typically done at the beginning of a notebook session. ```python %useLatestDescriptors %use lets-plot %use ggdsl(0.1.4-dev-45) %use dataframe ``` -------------------------------- ### Install kandy-echarts in Jupyter Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/echarts/echarts_cheatsheet.ipynb Use line magics to install the latest versions of kandy-echarts and other descriptors in your Jupyter notebook. ```python // use latest versions of library %useLatestDescriptors // kandy-echarts %use kandy-echarts ``` -------------------------------- ### Build and Test Library Source: https://github.com/kotlin/kandy/blob/main/CONTRIBUTING.md Run this command to build the Kandy library and execute all associated tests. ```bash ./gradlew build ``` -------------------------------- ### Serve Writerside Documentation Locally Source: https://github.com/kotlin/kandy/blob/main/util/kandy-samples-utils/README.md After building the Writerside web archive, unzip it and use `http-server` or Python's `http.server` module to serve the documentation locally. This is crucial for accurate testing as preview mode is not reliable. ```bash http-server ``` ```bash python -m http.server ``` -------------------------------- ### Generate Notebook Documentation Source: https://github.com/kotlin/kandy/blob/main/util/kandy-samples-utils/README.md Use this script to convert a Kotlin Notebook into .kt and .md files for Writerside documentation. The .kt file contains test classes for generating samples, and the .md file includes content with directives for code insertion and output display. ```bash python nb_to_doc.py doc_notebook.ipynb ``` -------------------------------- ### Install Kotlin Jupyter Kernel with Pip Source: https://github.com/kotlin/kandy/blob/main/docs/topics/Kandy-in-Jupyter-Notebook.md Install the Kotlin kernel for Jupyter Notebook using pip. This command makes the Kotlin kernel available for use within Jupyter. ```bash pip install kotlin-jupyter-kernel ``` -------------------------------- ### Configuring Tooltips and Background Styles Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Styles-Guide.md Shows how to configure tooltips with specific anchors and minimum widths, and how to set a custom background color and border for plot panels. ```kotlin plotGrid( listOf( df.plot { points { x(cty) y(hwy) color(fl) tooltips(anchor = Anchor.TOP_CENTER, minWidth = 50.0) {} } layout.title = "Tooltip: top-center" }, df.plot { points { x(cty) y(hwy) color(fl) tooltips(anchor = Anchor.TOP_CENTER, minWidth = 50.0) {} } layout { title = "Grey background" style { panel.background { borderLineColor = Color.PURPLE fillColor = Color.GREY } } } } ), nCol = 2 ) ``` -------------------------------- ### Install Kotlin Jupyter Kernel with Conda Source: https://github.com/kotlin/kandy/blob/main/docs/topics/Kandy-in-Jupyter-Notebook.md Install the Kotlin kernel for Jupyter Notebook using the conda package manager. This command ensures the kernel is available for creating Kotlin notebooks. ```bash conda install -c jetbrains kotlin-jupyter-kernel ``` -------------------------------- ### Initialize Sample Data for Raw Source Mapping Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Quick-Start-Guide.md Initializes sample data including months, number of days, and seasons. This data will be used for demonstrating raw source mapping in bar plots. ```kotlin val month = listOf( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ) val numberOfDays = listOf(31, 28, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30) val season = listOf( "winter", "winter", "spring", "spring", "spring", "summer", "summer", "summer", "autumn", "autumn", "autumn", "winter" ) ``` -------------------------------- ### Examples of CoordinatesTransformation Usage Source: https://github.com/kotlin/kandy/blob/main/docs/topics/apiRef/CoordinatesTransformation-API.md Illustrates how to apply different coordinate system transformations within a plot builder. ```APIDOC ## Examples ```kotlin plot { ... // Using the default Cartesian coordinate system transformation coordinatesTransformation = CoordinatesTransformation.cartesian() // Using a Cartesian coordinate system with a fixed aspect ratio transformation coordinatesTransformation = CoordinatesTransformation.cartesianFixed(ratio = 1.5) // Using a Cartesian coordinate system with flipped axes transformation coordinatesTransformation = CoordinatesTransformation.cartesianFlipped() } ``` ``` -------------------------------- ### Plotting with GeoMap Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Geo-Plotting-Guide.md Uses `geoMap` which applies Mercator projection by default for WGS84 coordinates, similar to the previous example. ```kotlin // This plot is identical // to the previous one. usaStates.plot { geoMap() } ``` -------------------------------- ### Create Simple Heatmap Source: https://github.com/kotlin/kandy/blob/main/docs/topics/samples/heatmap/Heatmap-Simple.md This snippet shows how to define columns for days and drinks and then plot them as a heatmap. Ensure you have the necessary Kandy dependencies. ```kotlin dataframe.plot { heatmap(days, drinks) } ``` -------------------------------- ### Read MPG Dataset Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Heatmap-Guide.md Loads the 'mpg' dataset from a CSV file into a DataFrame. Use this to start exploring the data. ```kotlin val mpgDF = DataFrame.readCsv("https://raw.githubusercontent.com/JetBrains/lets-plot-kotlin/master/docs/examples/data/mpg.csv") mpgDF.head(5) ``` -------------------------------- ### Configure Layout and Plot Layers Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/echarts/echarts_cheatsheet.ipynb Sets up layout options like legend position, tooltip, title, font, and size, then adds line and bar layers with specific aesthetics and colors. ```kotlin df.plot { layout { legend { right = 0.px } tooltip { trigger = Trigger.AXIS } title.text = "Layout settings" textStyle.fontFamily = FontFamily.MONOSPACE size = 900 to 600 } x(name) line { name = "Line" y(height) color = Color.RED width = 5.0 } bars { name = "Bars" y(height) color = LinearGradient(0.0, 0.0, 0.0, 1.0, listOf(Color.GREY, Color.ORANGE)) } } ``` -------------------------------- ### Create a sample dataset Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/samples/tiles/tiles_color_categories.ipynb Generates a Kotlin DataFrame with city, year, and value columns for plotting. ```kotlin val cities = listOf("Yerevan", "Berlin", "Amsterdam", "Paphos") val types = listOf("A", "B", "C") val random = kotlin.random.Random(42) val year22 = List(4) { types.random(random) } val year23 = List(4) { types.random(random) } val year24 = List(4) { types.random(random) } val dataset = dataFrameOf( "city" to cities, "2022" to year22, "2023" to year23, "2024" to year24 ).gather("2022", "2023", "2024").into("year", "value") ``` -------------------------------- ### Get CRS from Shapefile GeoDataFrame Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Geo-Plotting-Guide.md Retrieves the explicitly defined Coordinate Reference System (CRS) from a GeoDataFrame loaded from a Shapefile. ```kotlin worldCities.crs ``` -------------------------------- ### Create a Basic Heatmap Source: https://github.com/kotlin/kandy/blob/main/docs/topics/samples/tiles/Basic-Heatmap.md This snippet shows how to create a basic heatmap using Kandy. It involves defining categorical data for columns and rows and then plotting them using the heatmap function. Ensure you have the necessary Kandy libraries imported. ```kotlin val random = kotlin.random.Random(42) val cols = (List(20) { "col1" } + List(50) { "col2" } + List(70) { "col3" }).shuffled(random) val rows = (List(40) { "row1" } + List(80) { "row2" } + List(20) { "row3" }).shuffled(random) plot { heatmap(cols, rows) } ``` -------------------------------- ### Create a sample dataset Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/samples/points/jittered_points.ipynb Generates a Kotlin DataFrame with two columns, 'type' and 'value', for plotting. Includes random data generation for demonstration. ```kotlin val random = kotlin.random.Random(42) val dataset = dataFrameOf( "type" to List(50) { "a" } + List(50) { "b" }, "value" to List(50) { kotlin.random.Random.nextDouble(0.1, 0.6) } + List(50) { random.nextDouble(-0.5, 0.4) } ) ``` -------------------------------- ### Get CRS from GeoDataFrame Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Geo-Plotting-Guide.md Retrieves the Coordinate Reference System (CRS) from a GeoDataFrame. For GeoJSON, this is typically null, defaulting to WGS84. ```kotlin usaStates.crs ``` -------------------------------- ### Load MPG Dataset Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/guides/boxplot.ipynb Loads the MPG dataset from a CSV file for use in plotting examples. Displays the first few rows of the DataFrame. ```kotlin // Use "mpg" dataset val mpgDF = DataFrame.readCsv("https://raw.githubusercontent.com/JetBrains/lets-plot-kotlin/master/docs/examples/data/mpg.csv") mpgDF.head() ``` -------------------------------- ### Import necessary libraries Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/scatter_plot.ipynb Imports Lets-Plot and Kandy, along with Java's Random for data generation. ```python //%useLatestDescriptors %use lets-plot %use kandy(0.4.5-dev-31) import java.util.Random ``` -------------------------------- ### Get Distinct Geometry Types Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Geo-Plotting-Guide.md Lists the distinct geometry types present in the GeoDataFrame's geometry column, such as Polygon or MultiPolygon. ```kotlin usaStates.df.geometry.map { it::class }.distinct().toList() ``` -------------------------------- ### Create DataFrame Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/echarts/echarts_cheatsheet.ipynb Initializes a DataFrame with sample data for age, name, and height. ```kotlin val df = dataFrameOf( "name" to listOf("Alice", "Bob", "Charlie", "David"), "age" to listOf(17, 21, 15, 47), "height" to listOf(165, 183, 172, 169) ) ``` -------------------------------- ### Creating a DataFrame for Statistics Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Statistics-Guide.md Prepare your data by creating a DataFrame with sample and weights columns, which can be used with statistics APIs. ```kotlin val df = dataFrameOf("sample" to sample, "weights" to weights) ``` -------------------------------- ### Displaying Plots in a Grid Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/samples/line/comparing_line_vs_path_plots.ipynb Combines multiple plots into a single grid for easy comparison. This example displays the 'line' and 'path' plots side-by-side. ```kotlin import org.jetbrains.letsPlot.LetsPlot.plot import org.jetbrains.letsPlot.LetsPlot.plotGrid plotGrid(listOf(linePlot, pathPlot)) ``` -------------------------------- ### Generate Sample Data Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Plot-Bunch-Guide.md Generates sample data for plotting using a multivariate normal distribution. This data is used in subsequent plotting examples. ```kotlin val cov: Array = arrayOf( doubleArrayOf(1.0, 0.0), doubleArrayOf(0.0, 1.0) ) val means: DoubleArray = doubleArrayOf(0.0, 0.0) val random = JDKRandomGenerator(42) val xy = MultivariateNormalDistribution(random, means, cov).sample(400) val xs = xy.map { it[0] } val ys = xy.map { it[1] } ``` -------------------------------- ### Basic Plotting with Initial Data Source: https://github.com/kotlin/kandy/blob/main/docs/topics/Overview.md Illustrates the fundamental structure for creating a plot with initial data, specifying layers like lines, bars, points, or areas, and defining aesthetics within those layers. ```kotlin plot(data) { // layer (geoms) line[bars | points | area | pie | ...] { ... // aesthetics } line[bars | points | area | pie | ...] { ... } ... } ``` -------------------------------- ### Get Lets-Plot Information Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/qq_plots.ipynb Retrieves information about the loaded Lets-Plot version and frontend environment. This helps ensure compatibility and diagnose potential issues. ```kotlin LetsPlot.getInfo() // This prevents Krangl from loading an obsolete version of Lets-Plot classes. ``` -------------------------------- ### Basic Geom Violin with Parameter Variations (Kandy DSL) Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/geom_violin.ipynb Demonstrates the default geom_violin and its variations with different parameters like kernel, bw, and adjust using the Kandy DSL. ```kotlin val myPlots1 = listOf( mpg.create { plot { violin(drv, hwy, drawQuantiles=DRAW_QUANTILES) {} layout {title = "Default"} }}, mpg.create { plot { violin(drv, hwy, drawQuantiles=DRAW_QUANTILES, kernel=Kernel.EPANECHIKOV) {} layout {title = "kernel='epanechikov'"} }}, mpg.create { plot { violin(drv, hwy, drawQuantiles=DRAW_QUANTILES, bandWidth = BandWidth.ByValue(.1)) {} layout {title = "bw=0.1"} }}, mpg.create { plot { violin(drv, hwy, drawQuantiles=DRAW_QUANTILES, adjust = 2.0) {} layout {title = "adjust=2"} }}, ) plotGrid(myPlots1, 2, 400, 250) ``` -------------------------------- ### Basic Pie Chart Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/guides/pie.ipynb Demonstrates the fundamental structure for creating a pie chart with Kandy. It maps a 'value' to slice sizes and 'name' to fill colors. ```kotlin val dataset = dataFrameOf( "name" to listOf('a', 'b', 'c', 'd', 'b'), "value" to listOf(40, 90, 10, 50, 20) ) ``` ```kotlin dataset.plot { pie { slice(value) fillColor(name) } } ``` -------------------------------- ### Enable Kandy in Kotlin Notebook Source: https://github.com/kotlin/kandy/blob/main/docs/topics/Getting-Started.md Use this cell to enable Kandy and dataframe support in Kotlin Notebook. Ensure you have the Kotlin Notebook plugin installed. ```kotlin %use kandy // If you are using dataframe as data %use dataframe ``` -------------------------------- ### Basic Heatmap with Custom Settings Source: https://github.com/kotlin/kandy/blob/main/docs/topics/samples/heatmap/Heatmap-Settings.md Demonstrates how to create a heatmap with custom border lines and fill colors based on counts. It also shows how to format y-axis breaks. This snippet requires the Kandy library and a DataFrame. ```kotlin val df = DataFrame.readCsv( fileOrUrl = "https://raw.githubusercontent.com/Kotlin/dataframe/master/examples/idea-examples/titanic/src/main/resources/titanic.csv", delimiter = ';', parserOptions = ParserOptions(locale = java.util.Locale.FRENCH) ) df.plot { heatmap("embarked", "pclass") { borderLine { width = 0.8 color = Color.BLACK } fillColor(Stat.count) { scale = continuous(Color.WHITE..Color.RED) legend.name = "number of\n passangers" } } y.axis.breaks(df.get { "pclass"() }.distinct().toList(), format = "d") } ``` -------------------------------- ### Create a Smoothed Line Plot with `smoothLine` Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Smoothing-Guide.md Use the `smoothLine` layer as a shortcut for fast plotting of a smoothed line. This example demonstrates its basic usage. ```kotlin val smoothLineLayerPlot = plot { smoothLine(newXs, newYs) layout.title = "`smoothLine()` layer" } smoothLineLayerPlot ``` -------------------------------- ### Getting Lets-Plot Information Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/y_orientation.ipynb Retrieves and displays information about the loaded Lets-Plot version and its frontend environment. This is important to prevent conflicts with older Krangl versions. ```kotlin LetsPlot.getInfo() // This prevents Krangl from loading an obsolete version of Lets-Plot classes. ``` -------------------------------- ### Get City Points for New York and Los Angeles Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Geo-Plotting-Guide.md Uses the `takeCity` function to retrieve the Point geometries for New York and Los Angeles. ```Kotlin val newYork = takeCity("New York") val losAngeles = takeCity("Los Angeles") ``` -------------------------------- ### Boxplot with Flipped Coordinates (DSL) Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/coord_flip.ipynb Creates a boxplot using the Kotlin DSL with flipped coordinates. This example demonstrates the coordFlip() function within the DSL syntax. ```kotlin mpg.create { plot { boxplot(`class`, hwy) { orderBy(Stat.MIDDLE) borderLineColor(Color.fromHex("#579673")) fillColor(Color.fromHex("#9AC0B3")) borderLineWidth(1.5) } coordFlip() layout { title = "Flipped" size = 750 to 300 theme { xAxis.title { blank = true } } } } } ``` -------------------------------- ### Create a bubble chart with custom axes and size mapping Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/samples/points/bubble_chart.ipynb Configures a bubble chart using Lets-Plot, mapping 'week' to the x-axis, 'dayOfWeek' to the y-axis, and 'contributions' to the size of the bubbles. Customizes axis names, breaks, and the size scale. ```kotlin plot { points { x(week) { axis { name = "Week" breaks(week.distinct(), format = "d") } } y(dayOfWeek) { axis { name = "Day of week" breaks(listOf("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun").reversed()) } } color = Color.BLUE size(contributions) { scale = continuous(5.0..20.0, 1..15) legend.name = "Contributions" } } layout.title = "May GitHub contributions" } ``` -------------------------------- ### Create a Simple Density Plot Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/samples/densityPlot/densityPlot_simple.ipynb Generates a density plot from a list of 1000 Gaussian random numbers. Ensure Kandy is imported and set up before running. ```kotlin val random = java.util.Random(42) val sample = List(1000) {random.nextGaussian()} plot { densityPlot(sample) } ``` -------------------------------- ### Basic statCount2D and tile layer Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/guides/heatmap.ipynb Demonstrates creating a plot using `statCount2D` and `tile` layers for visualizing counts. ```kotlin val statCount2DAndTilePlot = df.plot { statCount2D(x = `class`, y = drv) { tile { fillColor(Stat.count) } } layout.title = "`statCount2D()` + `tile()` layer" } statCount2DAndTilePlot ``` -------------------------------- ### Configure MarkArea with Average, Max, and Min Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/echarts/marks.ipynb Sets up markArea configurations to highlight regions based on average, maximum, and minimum values. This helps in visually segmenting chart areas based on data ranges. ```kotlin markArea { areas = listOf( MarkArea("", MarkPoint(MarkType.AVERAGE), MarkPoint(MarkType.MAX)), MarkArea("", MarkPoint(MarkType.AVERAGE), MarkPoint(MarkType.MIN)) ) } ``` -------------------------------- ### Step Line Chart Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/echarts/lines.ipynb Creates a step line chart to visualize data that changes at discrete intervals. Supports different step types: START, MIDDLE, and END. ```kotlin val df = dataFrameOf( "month" to listOf("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), "start" to listOf(-9, -9, -4, 1, 7, 11, 15, 13, 8, 3, -2, -6), "middle" to listOf(-2, -1, 1, 5, 9, 12, 15, 14, 11, 6, 3, 0), "end" to listOf(4, 4, 6, 9, 13, 17, 19, 19, 16, 12, 8, 5) ) ``` ```kotlin df.plot { x(month) line { y(start) step = Step.START } line { y(middle) step = Step.MIDDLE } line { y(end) step = Step.END } } ``` -------------------------------- ### Basic Histogram with statBin Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/guides/histogram.ipynb Demonstrates creating a histogram using statBin and area layers. It maps x to Stat.x and y to Stat.count, with a fixed red fill color and alpha transparency. ```python plot { statBin(depthList, binsAlign = BinsAlign.center(500.0)) { // new `StatBin` dataset here area { // use `Stat.*` columns for mappings x(Stat.x) y(Stat.count) fillColor = Color.RED alpha = 0.5 } } } ``` -------------------------------- ### Boxplot with Default Coordinates (DSL) Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/coord_flip.ipynb Creates a boxplot using the Kotlin DSL, similar to the previous example but with a different API style. It displays 'hwy' by 'class' and sets a title. ```kotlin mpg.create { plot { boxplot(`class`, hwy) { orderBy(Stat.MIDDLE) borderLineColor(Color.fromHex("#579673")) fillColor(Color.fromHex("#9AC0B3")) borderLineWidth(1.5) } layout { title = "Default" size = 750 to 300 theme { xAxis.title { blank = true } } } } } ``` -------------------------------- ### Create Heatmap from DataFrame Source: https://github.com/kotlin/kandy/blob/main/docs/topics/samples/heatmap/Heatmap-Simple.md Visualize the frequency of data points across two discrete variables using a heatmap. This example uses a DataFrame and requires the Kandy plotting library. ```Kotlin val dataframe = dataFrameOf( "days" to listOf( "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun", "Sat", "Thu", "Fri", "Tue", "Wed", "Sun", "Mon", "Thu", "Sun", "Sat", "Tue", "Mon", "Thu", "Wed", "Fri", "Sat", "Tue", "Sun", "Fri", "Sat", "Thu", "Mon", "Wed", "Tue", "Thu", "Mon", "Sun", "Fri", "Wed", "Sat", "Tue", "Thu", "Sat", "Tue", "Sun", "Mon", "Wed", "Fri", "Thu", "Sat", "Thu", "Fri", "Sun", "Tue", "Sat", "Wed", "Mon", "Thu", "Wed", "Tue", "Sat", "Fri", "Sun", "Thu", "Mon", "Tue", "Fri", "Thu", "Wed", "Sun", "Sat", "Mon", "Tue", "Thu", "Tue", "Wed", "Sun", "Mon", "Thu", "Sat", "Fri", "Tue", "Thu", "Sun", "Fri", "Sat", "Mon", "Wed", "Tue", "Thu", "Sat", "Mon", "Tue", "Thu", "Fri", "Sun", "Wed", "Sat", "Sun", "Fri", "Tue", "Thu", "Sat", "Mon", "Wed", "Sun", "Mon", "Wed", "Sat", "Fri", "Thu", "Tue", "Sun", "Sat", ), "drinks" to listOf( "soda", "tea", "coffee", "tea", "soda", "tea", "coffee", "soda", "coffee", "soda", "tea", "coffee", "soda", "tea", "coffee", "tea", "coffee", "soda", "tea", "soda", "coffee", "tea", "soda", "coffee", "soda", "tea", "coffee", "tea", "soda", "coffee", "tea", "soda", "tea", "soda", "coffee", "tea", "soda", "coffee", "soda", "tea", "coffee", "soda", "tea", "soda", "coffee", "tea", "soda", "coffee", "soda", "coffee", "tea", "soda", "coffee", "soda", "tea", "coffee", "soda", "coffee", "tea", "soda", "tea", "soda", "coffee", "tea", "tea", "coffee", "soda", "tea", "coffee", "soda", "tea", "soda", "tea", "soda", "coffee", "soda", "tea", "coffee", "soda", "coffee", "tea", "coffee", "soda", "tea", "soda", "coffee", "soda", "tea", "coffee", "soda", "tea", "coffee", "tea", "soda", "coffee", "soda", "soda", "tea", "coffee", "soda", "tea", "coffee", "soda", "tea", "coffee", "tea", "soda", "coffee", "tea", "soda", "coffee", "soda" ) ) dataframe.plot { heatmap("days", "drinks") } ``` -------------------------------- ### Plotting Great Circle Path with Points Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/guides/geo_guide.ipynb Plots a great-circle path between two cities, overlaid on a map of US states. Highlights the start and end points of the path in red. ```kotlin val newYork = takeCity("New York") val losAngeles = takeCity("Los Angeles") val curveNY_LA = greatCircleLineString(newYork, losAngeles) usa48.plot { geoMap { alpha = 0.5 } geoPath(curveNY_LA) { width = 1.5 } geoPoints(listOf(newYork, losAngeles)) { size = 8.0 color = Color.RED } } ``` -------------------------------- ### Importing Libraries Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/density_2d.ipynb Imports necessary libraries for Lets-Plot and Apache Commons Math. ```python %useLatestDescriptors %use lets-plot %use ggdsl(0.1.4-dev-31) @file:DependsOn("org.apache.commons:commons-math3:3.6.1") ``` ```python import org.apache.commons.math3.distribution.MultivariateNormalDistribution ``` -------------------------------- ### Importing Libraries for Lets-Plot and DataFrame Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/guides/density_plot.ipynb Import necessary libraries for using Lets-Plot, DataFrame operations, and statistical calculations. This setup is required before generating data or performing statistical analysis. ```python %useLatestDescriptors %use kandy %use dataframe import org.apache.commons.math3.distribution.NormalDistribution import org.apache.commons.math3.distribution.UniformRealDistribution import org.jetbrains.kotlinx.statistics.dataframe.stat.mean ``` -------------------------------- ### Flipped Bar Chart (Default X-Orientation) Source: https://github.com/kotlin/kandy/blob/main/examples/notebooks/lets-plot/dev/y_orientation.ipynb Displays the same bar chart as the previous example but with a flipped coordinate system, effectively swapping x and y axes visually. The x-axis title is hidden. ```kotlin // Same but flipped coordinate system. orientationX + coordFlip() + hideXLabel ``` -------------------------------- ### Create a Basic Pie Chart Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Pie-Guide.md Generates a simple pie chart where slices are determined by 'value' and colored by 'name'. ```kotlin dataset.plot { pie { slice(value) fillColor(name) } } ``` -------------------------------- ### Generate Sample and Weights Source: https://github.com/kotlin/kandy/blob/main/docs/topics/guides/Statistics-Guide.md Generates a sample of 1000 values from a normal distribution and a list of 1000 weights from a uniform distribution. ```kotlin val sample = NormalDistribution().sample(1000).toList() val weights = UniformRealDistribution(0.0, 1.0).sample(1000).toList() ```