Dealing with unwanted sorting of x-axis in Plot.ly for R

After numerous attempts, I found myself unable to achieve success. The structure of my data frame is quite straightforward:

df <- as.data.frame(matrix(c("g","d","a","b","z",5,4,3,2,1),5,2))

library("plotly")
p <- plot_ly(data = df,x = ~V1,y = ~V2,type = "scatter",mode = "lines+markers") %>%
layout(title = "my title")
p

This results in:

However, I am looking to maintain the original order on the x-axis without it being sorted alphabetically, and instead display a decreasing graph.

Answer №1

Let's start by addressing the fact that a matrix is limited to containing data of only one class at a time. Therefore, if you have a matrix of strings that you are transforming into a data.frame, it will automatically convert your character matrix into a data.frame with columns represented as factors. The levels of these two columns will be sorted alphabetically for V1 and in increasing order for V2.

If you prefer not to directly modify the source data to fix this issue - as suggested in other responses, an alternative approach would be to use the categoryorder = argument from plotly's layout() function in the following manner:

library(plotly)
xform <- list(categoryorder = "array",
              categoryarray = df$V1)

plot_ly(data = df,
        x = ~V1,
        y = ~V2,
        type = "scatter",
        mode = "lines+markers") %>
        layout(title = "my title",
               xaxis = xform)

https://i.sstatic.net/lkCkl.png

Answer №2

> data_frame <- as.data.frame(matrix(c("g","d","a","b","z",5,4,3,2,1),5,2))
> structure_data(data_frame)
'data.frame':   5 obs. of  2 variables:
$ V1: Factor w/ 5 levels "a","b","d","g",..: 4 3 1 2 5
$ V2: Factor w/ 5 levels "1","2","3","4",..: 5 4 3 2 1
> data_frame$V1
[1] g d a b z
Levels: a b d g z
> data_frame$V1 <- ordered(data_frame$V1, c("g","d","a","b","z"))
> data_frame$V1
[1] g d a b z
Levels: g < d < a < b < z

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm looking to output a list of variables from a function using console.log in javascript within a node.js environment

function courseList(course1, course2, course3){ let course1=[{ Id: 154532, name:'basic digital marketing', duration: '15 days', price: 100000, }]; let course2=[{ Id: 154533, ...

How can I display milliseconds from a date in Angular2+?

I recently encountered an issue while working with a custom pipe that was used to display time. I attempted to modify it so that it could also show milliseconds: {{log.LogDate|jsonDate|date:'dd.MM.yyyy &nbsp; HH:mm:ss.sss'}} Here is the cod ...

Dividing CSV Data into Two File Outputs

I've got a CSV file that's structured like this: Docushare Host locale, created_at, version en,Wed Feb 21 17:25:36 UTC 2018,07.00.00.C1.609 User handle, client_data, docCountQuota User-12,,-2 Document handle,client_data,cfSpecialWords Document ...

Replace square brackets with a comma-separated list, excluding the first and last comma

I have been attempting to use console log in order to convert a list of items enclosed in square brackets into a comma-separated format. [Item 1][Item 2][Item 3][Item 4] ... .split(/[[\]]{1,2}/); However, the output I am currently receiving is as f ...

Disparity in React app: Misalignment between debugger and console output

Throughout the years, I've encountered this issue in various ways, and I have finally been able to articulate it. Take a look at the code snippet below: import React, {Component} from "react"; import aFunction from "./Function"; export default class ...

"Encountered a problem while setting up the Mailgun webhook to handle both multipart and URL encoded

I have been working on creating a web hook listener for Mailgun, and I encountered an issue when I realized that Mailgun can post webhooks using either multipart or x-www-form-urlencoded content-types. Currently, my code uses Multer to handle multipart b ...

d3 split bar chart with a horizontal layout

https://i.sstatic.net/P6qck.png I am interested in creating a split difference bar chart using d3 similar to the image provided. I have two input arrays - one for y-axis labels and one for data as shown below: data = [[35,90], [60,45], [80,90], [95,90]] m ...

Getting the most out of the ReporteRs R package: Enabling cell padding display in .docx files created

I've been utilizing the fantastic R package known as ReporteRs for quite some time now to create my R tables and plots. David Gohel truly excelled in his work here (check out David's site). The issue I'm currently facing is that I can' ...

Selenium Tips: Ensuring RemoteDriver Remains Connected to the Active Browser Tab

Currently working on a unique Windows application that utilizes voice commands to control web browsers. I am trying to figure out the best approach when users add tabs and modify the selected tab as needed. Unfortunately, RemoteDriver only supports swi ...

When does JSON overload become a problem?

Creating a bookmarking site similar to delicious has been my latest project. To ensure an optimized user experience, I have decided to fetch all the bookmarks from the database table and organize them into a JSON object containing essential data such as id ...

Generate a new item using an existing one

I am seeking to extract the desired output from the provided input: Input Configuration: var inputParams = { 'inputDetails' :[ { 'field' : 'specificationName', 'value' : 'strong'}, { ...

Why is URL Hash Navigation not functioning when linking to a different page's slide on the carousel?

Why isn't the #tag link being recognized? Even though the data-hash items are visible in the URL window, the script doesn't seem to pick them up. The standard script used on the carousel page is as follows: $(document).ready(function() { $( ...

Error 404: Jquery Fancy Box Not Found

Help needed with JQuery FancyBox: I encountered a 404 error when trying to enlarge small images. Here is the code that I used: <a class="fancybox-buttons" data-fancybox-group="button" href="images/gallery/1_b.png" style="margin-right:100px;"><im ...

Tip for closing Bootstrap modal using JavaScript?

I've been scouring various sources for an answer to what seems like a simple question... Here's the scenario: I have a Bootstrap modal that opens when clicked on a link created using the following code: <%= link_to "New Contact", new_contact ...

HTML anchor tag failing to redirect to specified link

I need to populate the URI property from an API result into an HTML format. I attempted to achieve this by calling a function and running a loop 3 times in order to display 3 links with the URI property of each object. However, the code is not functioning ...

JavaScript - Global Variable

Is it possible to declare and assign a value to a global variable in one JavaScript file and then reference it in another JavaScript file multiple times? Can Angular.js be utilized in a Velocity macro file, aside from HTML files? ...

Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this: { "comments": [ { "id": 1, "content": "lorem ipsum", "answers": [] }, { "id" ...

Tips for choosing elements based on the length of an array

When using an each function, I scan the DOM to find multiple elements with a specific className. Depending on the length of this ClassName, it will create an array that is either 2 or 4 elements long. I need to distinguish between these two types of elem ...

Developing an innovative LeaderBoard featuring personalized profile images

I am looking for a way to implement a dynamic leaderboard using JavaScript, where the Users Points are stored in variables and their ranks change automatically based on point updates... Here is the desired outcome: https://i.sstatic.net/uyCa8.png The id ...

Establish a global variable within the utils.js module in a Node.js environment

Hey there, I'm currently in the process of trying to figure out how to properly define a global variable in node.js. I am aware that it's not considered best practice, but in this specific scenario, it seems like the only way to go without involv ...