How to conditionally sort X-axis values in Matplotlib plot?How do I sort a list of dictionaries by a value of the dictionary?How do you change the size of figures drawn with matplotlib?How do I sort a dictionary by value?Hiding axis text in matplotlib plotsPeak detection in a 2D arrayHow to put the legend out of the plotHow to access environment variable values?Save plot to image file instead of displaying it using Matplotlib“Large data” work flows using pandasHow to make IPython notebook matplotlib plot inline
PhD: When to quit and move on?
What is the highest level of accuracy in motion control a Victorian society could achieve?
How do amateur satellites stay consistently in the amateur-sat bands acoss the globe?
What is the shape of the upper boundary of water hitting a screen?
Soda water first stored in refrigerator and then outside
Is it acceptable that I plot a time-series figure with years increasing from right to left?
Do I need transit visa for Dublin?
Was the 45.9°C temperature in France in June 2019 the highest ever recorded in France?
White's last move?
What is the maximum amount of diamond in one Minecraft game?
How to delete multiple process id of a single process?
Is there a minimum amount of electricity that can be fed back into the grid?
How did the IEC decide to create kibibytes?
Taking my Ph.D. advisor out for dinner after graduation
Bringing coumarin-containing liquor into the USA
Does the Milky Way orbit around anything?
Did Stalin kill all Soviet officers involved in the Winter War?
Why do people prefer metropolitan areas, considering monsters and villains?
Alternative to Willpower in Fighting Cravings
Computer name naming convention for security
Why do airports remove/realign runways?
Wouldn't putting an electronic key inside a small Faraday cage render it completely useless?
Can I Ready an attack action to trigger when the target Blinks back to the Material plane?
How predictable is $RANDOM really?
How to conditionally sort X-axis values in Matplotlib plot?
How do I sort a list of dictionaries by a value of the dictionary?How do you change the size of figures drawn with matplotlib?How do I sort a dictionary by value?Hiding axis text in matplotlib plotsPeak detection in a 2D arrayHow to put the legend out of the plotHow to access environment variable values?Save plot to image file instead of displaying it using Matplotlib“Large data” work flows using pandasHow to make IPython notebook matplotlib plot inline
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have the following DataFrame:
file size
abc1.txt 2.1 MB
abc2.txt 1.0 MB
abc3.txt 1.5 MB
abc4.txt 767.9 KB
When I plot these data (plt.plot(df['file'],df['size'])
), the values of KB and MB are obviously incorrectly ordered and are messed. How can I sort them so that the sorting would start from KB and would continue with MB?
767.9 KB 1.0 MB 1.5 MB 2.1 MB
python pandas matplotlib
add a comment |
I have the following DataFrame:
file size
abc1.txt 2.1 MB
abc2.txt 1.0 MB
abc3.txt 1.5 MB
abc4.txt 767.9 KB
When I plot these data (plt.plot(df['file'],df['size'])
), the values of KB and MB are obviously incorrectly ordered and are messed. How can I sort them so that the sorting would start from KB and would continue with MB?
767.9 KB 1.0 MB 1.5 MB 2.1 MB
python pandas matplotlib
add a comment |
I have the following DataFrame:
file size
abc1.txt 2.1 MB
abc2.txt 1.0 MB
abc3.txt 1.5 MB
abc4.txt 767.9 KB
When I plot these data (plt.plot(df['file'],df['size'])
), the values of KB and MB are obviously incorrectly ordered and are messed. How can I sort them so that the sorting would start from KB and would continue with MB?
767.9 KB 1.0 MB 1.5 MB 2.1 MB
python pandas matplotlib
I have the following DataFrame:
file size
abc1.txt 2.1 MB
abc2.txt 1.0 MB
abc3.txt 1.5 MB
abc4.txt 767.9 KB
When I plot these data (plt.plot(df['file'],df['size'])
), the values of KB and MB are obviously incorrectly ordered and are messed. How can I sort them so that the sorting would start from KB and would continue with MB?
767.9 KB 1.0 MB 1.5 MB 2.1 MB
python pandas matplotlib
python pandas matplotlib
asked Mar 25 at 20:17
ScalaBoyScalaBoy
9455 silver badges22 bronze badges
9455 silver badges22 bronze badges
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
First it's reading your numbers as a string, so any order wouldn't really make much sense and further the the space between the points is not representative.
Also in general I'd say it's poor practice to have different units on the same axis. Better to convert to the same unit:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame([['abc1.txt', '2.1 MB'],
['abc2.txt', '1.0 MB'],
['abc3.txt', '1.5 MB'],
['abc4.txt', '767.9 KB']], columns=["file", 'size'])
# This is a list comprehension that splits the number out of the string, converts it to a float,
# and divides it by 1000 if the other part of the string is 'KB'.
df['size_float'] = [float(x[0])/1000 if x[1]=='KB' else float(x[0]) for x in df['size'].str.split()]
plt.plot(df['file'],df['size_float'])
Shouldn't I divide by 1024?
– ScalaBoy
Mar 25 at 21:16
Lol, sure, if you want. :) It looks like your MB numbers are only accurate to one significant figure so it won't make much difference at the end of the day.
– Declan
Mar 25 at 21:20
add a comment |
df = pd.DataFrame('file': [1,2,3,4], 'size': ['2.1 MB', '1.0 MB', '1.5 MB', '767.9 KB'])
cv= '': 1, 'KB': 1e1, 'MB': 1e6, 'GB': 1e9, 'TB': 1e12
df['size_bytes'] = df['size'].apply(lambda x: float(x.split()[0])*cv[x.split()[1]]
if len(x.split())==2 else float(x))
fig, ax = plt.subplots()
plt.plot(df['file'],df['size_bytes'])
And if you want the y axis in human readable form
def to_human_readable(size):
power = 1000
n = 0
mem = 0 : '', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'
while size > power:
size /= power
n += 1
return "0 1".format(size, mem[n])
ax.set_yticklabels([to_human_readable(v) if v >= 0 else ' ' for v in
ax.get_yticks(minor=False)])
(In digital storage 1kb = 1000)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55345773%2fhow-to-conditionally-sort-x-axis-values-in-matplotlib-plot%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
First it's reading your numbers as a string, so any order wouldn't really make much sense and further the the space between the points is not representative.
Also in general I'd say it's poor practice to have different units on the same axis. Better to convert to the same unit:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame([['abc1.txt', '2.1 MB'],
['abc2.txt', '1.0 MB'],
['abc3.txt', '1.5 MB'],
['abc4.txt', '767.9 KB']], columns=["file", 'size'])
# This is a list comprehension that splits the number out of the string, converts it to a float,
# and divides it by 1000 if the other part of the string is 'KB'.
df['size_float'] = [float(x[0])/1000 if x[1]=='KB' else float(x[0]) for x in df['size'].str.split()]
plt.plot(df['file'],df['size_float'])
Shouldn't I divide by 1024?
– ScalaBoy
Mar 25 at 21:16
Lol, sure, if you want. :) It looks like your MB numbers are only accurate to one significant figure so it won't make much difference at the end of the day.
– Declan
Mar 25 at 21:20
add a comment |
First it's reading your numbers as a string, so any order wouldn't really make much sense and further the the space between the points is not representative.
Also in general I'd say it's poor practice to have different units on the same axis. Better to convert to the same unit:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame([['abc1.txt', '2.1 MB'],
['abc2.txt', '1.0 MB'],
['abc3.txt', '1.5 MB'],
['abc4.txt', '767.9 KB']], columns=["file", 'size'])
# This is a list comprehension that splits the number out of the string, converts it to a float,
# and divides it by 1000 if the other part of the string is 'KB'.
df['size_float'] = [float(x[0])/1000 if x[1]=='KB' else float(x[0]) for x in df['size'].str.split()]
plt.plot(df['file'],df['size_float'])
Shouldn't I divide by 1024?
– ScalaBoy
Mar 25 at 21:16
Lol, sure, if you want. :) It looks like your MB numbers are only accurate to one significant figure so it won't make much difference at the end of the day.
– Declan
Mar 25 at 21:20
add a comment |
First it's reading your numbers as a string, so any order wouldn't really make much sense and further the the space between the points is not representative.
Also in general I'd say it's poor practice to have different units on the same axis. Better to convert to the same unit:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame([['abc1.txt', '2.1 MB'],
['abc2.txt', '1.0 MB'],
['abc3.txt', '1.5 MB'],
['abc4.txt', '767.9 KB']], columns=["file", 'size'])
# This is a list comprehension that splits the number out of the string, converts it to a float,
# and divides it by 1000 if the other part of the string is 'KB'.
df['size_float'] = [float(x[0])/1000 if x[1]=='KB' else float(x[0]) for x in df['size'].str.split()]
plt.plot(df['file'],df['size_float'])
First it's reading your numbers as a string, so any order wouldn't really make much sense and further the the space between the points is not representative.
Also in general I'd say it's poor practice to have different units on the same axis. Better to convert to the same unit:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame([['abc1.txt', '2.1 MB'],
['abc2.txt', '1.0 MB'],
['abc3.txt', '1.5 MB'],
['abc4.txt', '767.9 KB']], columns=["file", 'size'])
# This is a list comprehension that splits the number out of the string, converts it to a float,
# and divides it by 1000 if the other part of the string is 'KB'.
df['size_float'] = [float(x[0])/1000 if x[1]=='KB' else float(x[0]) for x in df['size'].str.split()]
plt.plot(df['file'],df['size_float'])
answered Mar 25 at 21:11
DeclanDeclan
958 bronze badges
958 bronze badges
Shouldn't I divide by 1024?
– ScalaBoy
Mar 25 at 21:16
Lol, sure, if you want. :) It looks like your MB numbers are only accurate to one significant figure so it won't make much difference at the end of the day.
– Declan
Mar 25 at 21:20
add a comment |
Shouldn't I divide by 1024?
– ScalaBoy
Mar 25 at 21:16
Lol, sure, if you want. :) It looks like your MB numbers are only accurate to one significant figure so it won't make much difference at the end of the day.
– Declan
Mar 25 at 21:20
Shouldn't I divide by 1024?
– ScalaBoy
Mar 25 at 21:16
Shouldn't I divide by 1024?
– ScalaBoy
Mar 25 at 21:16
Lol, sure, if you want. :) It looks like your MB numbers are only accurate to one significant figure so it won't make much difference at the end of the day.
– Declan
Mar 25 at 21:20
Lol, sure, if you want. :) It looks like your MB numbers are only accurate to one significant figure so it won't make much difference at the end of the day.
– Declan
Mar 25 at 21:20
add a comment |
df = pd.DataFrame('file': [1,2,3,4], 'size': ['2.1 MB', '1.0 MB', '1.5 MB', '767.9 KB'])
cv= '': 1, 'KB': 1e1, 'MB': 1e6, 'GB': 1e9, 'TB': 1e12
df['size_bytes'] = df['size'].apply(lambda x: float(x.split()[0])*cv[x.split()[1]]
if len(x.split())==2 else float(x))
fig, ax = plt.subplots()
plt.plot(df['file'],df['size_bytes'])
And if you want the y axis in human readable form
def to_human_readable(size):
power = 1000
n = 0
mem = 0 : '', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'
while size > power:
size /= power
n += 1
return "0 1".format(size, mem[n])
ax.set_yticklabels([to_human_readable(v) if v >= 0 else ' ' for v in
ax.get_yticks(minor=False)])
(In digital storage 1kb = 1000)
add a comment |
df = pd.DataFrame('file': [1,2,3,4], 'size': ['2.1 MB', '1.0 MB', '1.5 MB', '767.9 KB'])
cv= '': 1, 'KB': 1e1, 'MB': 1e6, 'GB': 1e9, 'TB': 1e12
df['size_bytes'] = df['size'].apply(lambda x: float(x.split()[0])*cv[x.split()[1]]
if len(x.split())==2 else float(x))
fig, ax = plt.subplots()
plt.plot(df['file'],df['size_bytes'])
And if you want the y axis in human readable form
def to_human_readable(size):
power = 1000
n = 0
mem = 0 : '', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'
while size > power:
size /= power
n += 1
return "0 1".format(size, mem[n])
ax.set_yticklabels([to_human_readable(v) if v >= 0 else ' ' for v in
ax.get_yticks(minor=False)])
(In digital storage 1kb = 1000)
add a comment |
df = pd.DataFrame('file': [1,2,3,4], 'size': ['2.1 MB', '1.0 MB', '1.5 MB', '767.9 KB'])
cv= '': 1, 'KB': 1e1, 'MB': 1e6, 'GB': 1e9, 'TB': 1e12
df['size_bytes'] = df['size'].apply(lambda x: float(x.split()[0])*cv[x.split()[1]]
if len(x.split())==2 else float(x))
fig, ax = plt.subplots()
plt.plot(df['file'],df['size_bytes'])
And if you want the y axis in human readable form
def to_human_readable(size):
power = 1000
n = 0
mem = 0 : '', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'
while size > power:
size /= power
n += 1
return "0 1".format(size, mem[n])
ax.set_yticklabels([to_human_readable(v) if v >= 0 else ' ' for v in
ax.get_yticks(minor=False)])
(In digital storage 1kb = 1000)
df = pd.DataFrame('file': [1,2,3,4], 'size': ['2.1 MB', '1.0 MB', '1.5 MB', '767.9 KB'])
cv= '': 1, 'KB': 1e1, 'MB': 1e6, 'GB': 1e9, 'TB': 1e12
df['size_bytes'] = df['size'].apply(lambda x: float(x.split()[0])*cv[x.split()[1]]
if len(x.split())==2 else float(x))
fig, ax = plt.subplots()
plt.plot(df['file'],df['size_bytes'])
And if you want the y axis in human readable form
def to_human_readable(size):
power = 1000
n = 0
mem = 0 : '', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'
while size > power:
size /= power
n += 1
return "0 1".format(size, mem[n])
ax.set_yticklabels([to_human_readable(v) if v >= 0 else ' ' for v in
ax.get_yticks(minor=False)])
(In digital storage 1kb = 1000)
answered Mar 25 at 21:39
mujjigamujjiga
4,3552 gold badges14 silver badges22 bronze badges
4,3552 gold badges14 silver badges22 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55345773%2fhow-to-conditionally-sort-x-axis-values-in-matplotlib-plot%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown